当前位置: 首页 > news >正文

Gridview常用技巧

ContractedBlock.gif ExpandedBlockStart.gif Code
1.gridview行绑定删除事件 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        
int i; 
        
//执行循环,保证每条数据都可以更新 
        for (i = 0; i < GridView1.Rows.Count; i++
        { 
            
//首先判断是否是数据行 
            if (e.Row.RowType == DataControlRowType.DataRow) 
            { 
                
//当鼠标停留时更改背景色 
                e.Row.Attributes.Add("onmouseover""c=this.style.backgroundColor;this.style.backgroundColor='#dee9f9'"); 
                
//当鼠标移开时还原背景色 
                e.Row.Attributes.Add("onmouseout""this.style.backgroundColor=c"); 
            } 
        } 
­
        
if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
     
            
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) 
            { 
                ((LinkButton)e.Row.Cells[
8].Controls[0]).Attributes.Add("onclick""javascript:return confirm('你确认要删除: \"" + e.Row.Cells[5].Text + "\" 的 \""+ e.Row.Cells[1].Text +"\" 的等级考试报名吗?')"); 
            } 
        } 
   
    } 
­
     
    
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
        SqlConnection con 
= new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["strcon"]); 
        con.Open(); 
        
string id = GridView1.DataKeys[e.RowIndex].Value.ToString(); 
        SqlCommand scd 
= new SqlCommand("delete  from ts_xs_fourSixGradeTextSignUp where id='" + id + "'", con); 
        scd.ExecuteNonQuery(); 
        con.Close(); 
        
this.bind(); 

­
    
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 
    { 
        
string id = GridView1.DataKeys[e.NewEditIndex].Value.ToString(); 
        Response.Write(
"<script>window.open('std_addGradeTestSignUpInfoList.aspx?id=" + id + "','','width=740,height=410')</script>"); 
        Response.Write(
"<script>location='javascript:history.go(-1)'</script>"); 
    } 
2.JavaScript弹出对话框 
Page.ClientScript.RegisterStartupScript(
this.GetType(), "alert""<script language=javascript>alert('回复留言失败!');</script>"); 
   Response.Write(
"<script>alert('登陆成功!');history.go(-1);</script>"); 
         
3.GridView和CheckBox结合: 
protected void CheckBox2_CheckedChanged(object sender, EventArgs e) 

for (int i = 0; i <= GridView1.Rows.Count - 1; i++
    { 
     CheckBox cbox 
= (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); 
      
if (CheckBox2.Checked == true
          {cbox.Checked 
= true;} 
      
else 
      { cbox.Checked 
= false;}   


4.留言板: 
Gridview自定义模板 
<%@ Import Namespace="System.Data" %> 
<div id="div2" runat=server>         
<asp:ScriptManager ID="ScriptManager1" runat="server" > </asp:ScriptManager> 
<asp:UpdatePanel ID="UpdatePanel1" runat="server"UpdateMode="Conditional"> 
<ContentTemplate> 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="200px" OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging=true PageSize="6" GridLines=None> 
<Columns> 
<asp:TemplateField>                   
   
<ItemTemplate> 
     
<table border="0" cellpadding="0" height=150 width=800> 
       
<tr><td rowspan="3" style="width:120px" > 
<asp:Image ID="Image2" runat="server" ImageUrl='<%#((DataRowView)Container.DataItem)["PicUrl"]%>'/><br/> 
<div id="div12" style="text-align:left">         
昵称:
<%# ((DataRowView)Container.DataItem)["UserName"]%> 
­
E
-mail:<%# ((DataRowView)Container.DataItem)["userEmail"]%>   
来自:
<%# ((DataRowView)Container.DataItem)["UserIP"].ToString().Substring(0, ((DataRowView)Container.DataItem)["UserIP"].ToString().LastIndexOf(".")+1)%> 
</div></td>   
<td colspan="2" style="height: 20px; text-align:left;"> 
  
<asp:Image ID="Image3" runat="server" ImageUrl='<%# ((DataRowView)Container.DataItem)["faceurl"]%>'/> 
发表于:
<%# ((DataRowView)Container.DataItem)["Addtime"]%> 
      
</td></tr> 
  
<tr><td colspan="2" valign="top" height="50" style="text-align:left;"> 
   
<%# ((DataRowView)Container.DataItem)["UserContent"%> 
­
<div id="main1"  style="margin-top:40px;border:#ff9966 1px solid;" visible='<%#(((DataRowView)Container.DataItem)["adminReply"]).ToString()==""?false:true %>' runat=server > <font color=red> 管理员回复:<br/><%# ((DataRowView)Container.DataItem)["adminReply"]%></font>   </div> 
  
</td></tr></table> 
  
</ItemTemplate> 
</asp:TemplateField> 
</Columns></asp:GridView> 
</ContentTemplate>           
<Triggers> 
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="PageIndexChanging"/> 
            
</Triggers> 
  
</asp:UpdatePanel>             
       
</div> 
5.从一个另外一个页面获取获取gridveiw中数据 
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="8" AutoGenerateColumns="False" EmptyDataText="暂时没有留言" OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None" Width="700px" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound"> 
<Columns> 
<asp:HyperLinkField DataNavigateUrlFields="id"//绑定到超链接的属性字段DataNavigateUrlFormatString="UserInfo.aspx?id={0}" 
//对绑定的超链接NavigateUrl属性值的格式设置以便在UserInfo.aspx页面用Request.QueryString["id"]获取gridview的指定列主键id   
{public void init() 
//用Request.QueryString["id"].ToString()获取gridview的主键id   
string id = Request.QueryString["id"].ToString(); 
   
if (id != null && id != ""
   { 
string sql = "select * from message where id=" + id; 
    DataSet ds 
= db.GetData(sql, "message"); 
    
this.username.Text = ds.Tables["message"].Rows[0]["username"].ToString(); 
//DataRowView rv = ds.Tables["0"].DefaultView[0]; 
//this.username.Text = rv["username"].ToString();     


DataTextField
="username" HeaderText="用户" Target="_self" /> 
<asp:BoundField DataField="useremail" HeaderText="邮件" /> 
<asp:BoundField DataField="userurl" HeaderText="个人网站" /> 
<asp:CommandField ShowDeleteButton="True" />  </Columns> 
</asp:GridView>   
­
<asp:TemplateField> 
       
<ItemTemplate> 
           
<asp:LinkButton ID="lbtnViewStudents" runat="server"  CommandArgument='<%#Eval("pc_id")%>'>查看选课学生</asp:LinkButton> 
       
</ItemTemplate> 
</asp:TemplateField> 
#region 查看选课学生 
    
protected void gv_TeachCoures_RowCommand(object sender, GridViewCommandEventArgs e) 
    { 
        Response.Redirect(
"ViewStudentChoose.aspx?pc_id=" + e.CommandArgument.ToString()); 
    } 
   
#endregion 
<asp:TemplateField> 
<HeaderTemplate > 
教师编号 
</HeaderTemplate> 
<ItemTemplate > 
<a id="A1" href= "#" 
onclick
='javascript:showDetail(<%#DataBinder.Eval(Container.DataItem, "id")%>);'><font style=" text-decoration: underline;"><asp:label id= "laid" runat= "server"  Text= '<%#Bind("jsgh")%>' Width="160px"> </asp:label> 
</font></a> 
</ItemTemplate> 
</asp:TemplateField> 
­
<asp:TemplateField HeaderText="编辑"> 
    
<ItemTemplate> 
            
<asp:Button ID='ButtonD' runat="server" CssClass="button"  CommandName="del"   CommandArgument=<%#bind("id")%> Text="删除" /> 
     
</ItemTemplate> 
</asp:TemplateField> 
     
/// 删除事件 
protected void gvTeacher_RowCommand(object sender, GridViewCommandEventArgs e) 
        { 
            
if (e.CommandName == "del"
            { 
                
int id = Convert.ToInt32(e.CommandArgument.ToString()); 
                teacherBll.Delete(id); 
                
this.pager.CurPage = this.ddlstPage.SelectedIndex + 1
                
this.strWhere = this.hfdQeuryCondition.Value; 
                FillGridView(); 
            } 
­
        } 
­
  
6.删除gridveiw选中行 
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
        
string sql = "select * from message"
        OleDbDataAdapter da 
= new OleDbDataAdapter(sql,conn); 
        OleDbCommandBuilder oc 
= new OleDbCommandBuilder(da); 
        DataSet ds 
= new DataSet(); 
        da.Fill(ds,
"b"); 
        DataRow row 
= ds.Tables["b"].Rows[e.RowIndex]; 
        row.Delete(); 
        da.Update(ds,
"b"); 
        
this.ShowInfo(); 

7.//设置gridview中指定列的内容和鼠标移动是改变行颜色 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 

//int i; 
////执行循环,保证每条数据都可以更新 
//for (i = 0; i < GridView1.Rows.Count; i++) 
//
if (e.Row.RowType == DataControlRowType.DataRow) 
{   
e.Row.Attributes.Add(
"onmouseover","this.style.backgroundColor='#E6F5FA'"); 
e.Row.Attributes.Add(
"onmouseout""this.style.backgroundColor='#FFFFFF'"); 
if (e.Row.Cells[4].Text.Trim() == "0"

   {e.Row.Cells [
4].Text=" <font color=red>隐藏</font>";} 
else 
  {e.Row .Cells[
4].Text="公开";} 
   }       ((LinkButton)(e.Row.Cells[
6].Controls[0])).Attributes.Add("onclick","return confirm('确定要删除吗?')"); 
         
    } 

8.GridView实现删除时弹出确认对话框: 
双击GridView的OnRowDataBound事件; 
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示: 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{   
//如果是绑定数据行 
    if (e.Row.RowType == DataControlRowType.DataRow) 
   { 
      
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) 
    { 
        ((LinkButton)e.Row.Cells[
6].Controls[0]).Attributes.Add("onclick""javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')"); 
     } 
   } 

    
/// GV 数据绑定事件 
protected void gvTeacher_RowDataBound(object sender, GridViewRowEventArgs e) 
   { 
        
//首先判断是否是数据行 
       if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
  
//当鼠标停留时更改背景色 
e.Row.Attributes.Add("onmouseover"" this.style.backgroundColor='#C0FAFF'"); 
   
//当鼠标移开时还原背景色 
e.Row.Attributes.Add("onmouseout""this.style.backgroundColor=c"); 
//编辑按钮onclick事件 
string url = "TeacherAdd.aspx?id=" + this.gvTeacher.DataKeys[e.Row.RowIndex].Value; 
string OnClientClick = CommonPage.Fpage_f_win_opendialog_returnvalue(this.Page, url, 850600); 
­
­
//窗口事件 
public static string Fpage_f_win_opendialog_returnvalue(System.Web.UI.Page page, string URL, int width, int height) 

string js2 = "javascript:"
js2 
+= string.Format("res=window.showModalDialog(\"{0}\",window,\" 
status:no;resizable:no;dialogWidth:{
1}px;dialogHeight:{2}px\");", URL, width.ToString(), height.ToString()); 
  js2 
+= "if (res==\"pleasefresh\")" + " {" + " refresh();" + "}"
  
return js2; 

例子: 
//新增按钮Onclick事件字符串 
string OnAddClientClick =Fpage_f_win_opendialog_returnvalue(this.Page, "TeacherAdd.aspx"850600); 
  
//绑定新增按钮btnAdd Onclick事件 
this.btnAdd.Attributes.Add("onclick", OnAddClientClick); 
              ((HtmlInputButton)e.Row.FindControl(
"ButtonE")).Attributes.Add("onclick", OnClientClick); 
//删除按钮onclick事件 
string ondeleteclick = "javascript:return confirm('是否删除教师" + e.Row.Cells[2].Text + "?')";              ((Button)e.Row.FindControl("ButtonD")).Attributes.Add("onclick",ondeleteclick; 
    } 

         
9.GridView加入自动求和求平均值小计   
private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
         
        
if (e.Row.RowIndex >= 0
        { 
            sum 
+= Convert.ToDouble(e.Row.Cells[6].Text); 
        } 
        
else if (e.Row.RowType == DataControlRowType.Footer) 
        { 
            e.Row.Cells[
5].Text = "总薪水为:"
            e.Row.Cells[
6].Text = sum.ToString(); 
            e.Row.Cells[
3].Text = "平均薪水为:"
            e.Row.Cells[
4].Text = ((int)(sum / GridView1.Rows.Count)).ToString(); 
             
        } 

10.配置文件连接数据和取得web.config键值 
<connectionStrings> 
    
<!-- SQL connection string for Inventory database lookup --> 
    
<add name="SQLConnetionString" connectionString="server=(local);user id=sa;password=;database=OfficeAutoDB;min pool size=4;max pool size=4;packet size=3072" providerName="System.Data.SqlClient"> 
    
</add> 
  
</connectionStrings> 
­
  
<appSettings> 
    
<add key ="DSExcel" value="Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" ></add> 
    
<add key="Excel" value ="App_Data\excel.xls"></add> 
  
</appSettings> 
private readonly string DSExcel = ConfigurationSettings.AppSettings["DSExcel"].ToString(); 
    
private readonly string Excel = ConfigurationSettings.AppSettings["Excel"].ToString(); 
    
public static string sqlcon = ConfigurationManager.ConnectionStrings["SQLConnetionString"].ToString(); 
11.GridView数据导入Excel/Excel数据读入GridView 
由于是文件操作所以要引入名称空间IO和Text 
using System.IO; 
using System.Text; 
using System.Drawing; 
//导入Excel 
protected void Button1_Click(object sender, EventArgs e) 
    { 
        Export(
"application/ms-excel""学生成绩报表.xls"); 
    } 
­
    
private void Export(string FileType, string FileName) 
    { 
        Response.Charset 
= "GB2312"
        Response.ContentEncoding 
= System.Text.Encoding.UTF7; 
        Response.AppendHeader(
"Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); 
        Response.ContentType 
= FileType; 
        
this.EnableViewState = false
        StringWriter tw 
= new StringWriter(); 
        HtmlTextWriter hw 
= new HtmlTextWriter(tw); 
        GridView1.RenderControl(hw); 
        Response.Write(tw.ToString()); 
        Response.End(); 
    } 
//如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内 
    public override void VerifyRenderingInServerForm(Control control) 
    { 
    } 
//读取Excel数据 
private DataSet CreateDataSource() 
    { 
        
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data\\excel.xls"+ ";Extended Properties=Excel 8.0 ;"
        OleDbConnection olecon 
= new OleDbConnection(strCon); 
       
// string ExcelDbPath = DSExcel + Server.MapPath(Excel) + ";"; 
       
// OleDbConnection olecon = new OleDbConnection(ExcelDbPath); 
        OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", olecon); 
        DataSet myds 
= new DataSet(); 
        myda.Fill(myds); 
        
return myds; 
­
    } 
    
protected void Button1_Click(object sender, EventArgs e) 
    { 
        GridView1.DataSource 
= CreateDataSource(); 
        GridView1.DataBind(); 
­

11.GridView动态分页取出当前显示需要显示的记录 
private DataSet GetCachingData(int nStartIndex, int nMaxIndex) 
    { 
        
string sql = "select * from Files"
        SqlConnection cn 
= new SqlConnection(sqlcon); 
        
string counttext = "select count(*) as countFiles from Files"
        SqlCommand cmd 
= new SqlCommand(counttext, cn); 
        SqlDataAdapter adapter 
= new SqlDataAdapter(sql, cn); 
        DataSet ds 
= new DataSet(); 
        cn.Open(); 
        
int nMaxcount = Int32.Parse(cmd.ExecuteScalar().ToString()); 
        
int nPagecount = nMaxcount / GridView1.PageSize; 
        
if (GridView1.PageSize * nPagecount < nMaxcount) 
        { 
            nPagecount
++
­
        } 
        adapter.Fill(ds, nStartIndex, nMaxIndex, 
"Files"); 
        cn.Close(); 
        
return (ds); 
         
    } 
    
private void BindData() 
    { 
        DataSet ds 
= new DataSet(); 
        
if (GridView1.PageIndex == 0
        { 
            ds 
= GetCachingData(0, GridView1.PageSize); 
        } 
        
else 
        { 
            
if (GridView1.PageIndex > 1
            { 
                ds 
= GetCachingData((GridView1.PageIndex - 1* GridView1.PageSize, GridView1.PageSize); 
            } 
        } 
        
if (ds != null && ds.Tables.Count > 0
        { 
            GridView1.DataSource 
= ds; 
            GridView1.DataBind(); 
        } 
    } 
//选中checkbox 
private ArrayList GetSelected() 
  { ArrayList selected 
= new ArrayList(); 
for (int i = 0; i <= gvTeacher.Rows.Count - 1; i++
      { 
          
if (((CheckBox)gvTeacher.Rows[i].FindControl("chkBox1")).Checked) 
               selected.Add(Convert.ToInt32(gvTeacher.DataKeys[i].Value)); 
       } 
     
return selected; 
   } 

转载于:https://www.cnblogs.com/hubcarl/archive/2009/03/28/1423933.html

相关文章:

  • Open xml 操作Excel 透视表(Pivot table)-- 实现Excel多语言报表
  • Delphi 数据类型列表
  • 在struts1.1框架下,利用smartupload实现文件的上传(可以是多个文件)
  • [转帖]三星F488E的JAVA安装方法
  • UICheckBox 用法解析
  • MySQL笔记系列:数据库概述
  • JOIN 和 WHERE?简单的问题也有学问。
  • 图像替换技术
  • WCF 第四章 绑定 创建一个自定义绑定
  • 健康小常识
  • 似水流年 ? Chrome调试大全
  • 关于gulp复制文件时把整个目录结构都复制的问题解决
  • java 求集合真子集_高中数学第2讲:子集与并集
  • 网线传输速度测试_如何鉴定网线好坏?怎样测网线电阻?
  • 展示 用户画像_智能时代如何做好精准营销?从用户画像智能化开始
  • 78. Subsets
  • Android路由框架AnnoRouter:使用Java接口来定义路由跳转
  • Codepen 每日精选(2018-3-25)
  • CSS魔法堂:Absolute Positioning就这个样
  • Dubbo 整合 Pinpoint 做分布式服务请求跟踪
  • in typeof instanceof ===这些运算符有什么作用
  • Java超时控制的实现
  • Linux各目录及每个目录的详细介绍
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 基于遗传算法的优化问题求解
  • ------- 计算机网络基础
  • 前端相关框架总和
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 使用agvtool更改app version/build
  • 通信类
  • 学习笔记TF060:图像语音结合,看图说话
  • 优化 Vue 项目编译文件大小
  • 7行Python代码的人脸识别
  • Hibernate主键生成策略及选择
  • 阿里云API、SDK和CLI应用实践方案
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • ​queue --- 一个同步的队列类​
  • #1014 : Trie树
  • #中的引用型是什么意识_Java中四种引用有什么区别以及应用场景
  • (70min)字节暑假实习二面(已挂)
  • (八十八)VFL语言初步 - 实现布局
  • (黑马C++)L06 重载与继承
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (十五)Flask覆写wsgi_app函数实现自定义中间件
  • .NET Core 将实体类转换为 SQL(ORM 映射)
  • .NET 使用 XPath 来读写 XML 文件
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .Net接口调试与案例
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .vue文件怎么使用_我在项目中是这样配置Vue的
  • @Autowired多个相同类型bean装配问题
  • @value 静态变量_Python彻底搞懂:变量、对象、赋值、引用、拷贝
  • @zabbix数据库历史与趋势数据占用优化(mysql存储查询)
  • [ CTF ] WriteUp-2022年春秋杯网络安全联赛-冬季赛
  • [ NOI 2001 ] 食物链