GridView从入门到精
工作中常常用到数据绑定,而使用GridView的次数最多,现在把GridView的一些常用方法写下来。
新建一个asps的页面。如下
<body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br/> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" > <Columns> <asp:TemplateField > <HeaderTemplate> <asp:CheckBox runat="server" Text="选择" ID="checkall" TextAlign="Left" AutoPostBack="true" OnCheckedChanged="CheckAll" /> </HeaderTemplate> <ItemTemplate > <asp:CheckBox id="danxuan" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="OrderId" /> <asp:HyperLinkField DataTextField="OrderId" HeaderText="IP地址" DataNavigateUrlFormatString="WebForm1.aspx?HangBiaoShi={0}" DataNavigateUrlFields="OrderId" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" Target="_blank" > <HeaderStyle HorizontalAlign="Center"></HeaderStyle> <ItemStyle HorizontalAlign="Center"></ItemStyle> </asp:HyperLinkField> <asp:BoundField DataField="OrderDate" HeaderText="日期" /> <asp:BoundField DataField="userid" HeaderText="文件编号" /> <asp:BoundField DataField="totalprice" HeaderText="单价" /> <asp:BoundField DataField="postaddress" HeaderText="地址" /> <asp:BoundField DataField="state" HeaderText="单" /> </Columns> </asp:GridView> </div> <div> <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" /> </div> </form> </body>
后台绑定数据如下
string conn = "Data Source=.;Initial Catalog=bookshop;User ID=sa;Password=123456"; protected void Button1_Click(object sender, EventArgs e) { using (SqlConnection coonn = new SqlConnection(conn)) { string sql = "select * from orders"; using (SqlCommand cmd = new SqlCommand(sql, coonn)) { SqlDataAdapter sd = new SqlDataAdapter(cmd); DataTable tb = new DataTable(); sd.Fill(tb); GridView1.DataSource = tb; GridView1.DataBind(); } } }
连接数据库,查询一个表,绑定到GridView上
第一个功能,全选和全不选,这个常用到,在GridView里面回一个头模板,在头模板里面放一个CheckBox,写一个oncheckedchanged事件
<HeaderTemplate>
<asp:CheckBox runat="server" Text="选择" ID="checkall" TextAlign="Left" AutoPostBack="true" OnCheckedChanged="CheckAll" />
</HeaderTemplate>
然后在加一个项模板在项模板中新增一个Checkbox,
<ItemTemplate >
<asp:CheckBox id="danxuan" runat="server" />
</ItemTemplate>
记住在最外面还要加一个 <asp:TemplateField ItemStyle-HorizontalAlign="Center">模板。
现在写Checkbox单选事件的后台代码
protected void CheckAll(object sender, EventArgs e) { CheckBox cb; if (((CheckBox)sender).Checked == false) { for (int i = 0; i < GridView1.Rows.Count; i++) { cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("danxuan"); cb.Checked = false; } } if (((CheckBox)sender).Checked == true) { for (int i = 0; i < GridView1 .Rows.Count; i++) { cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("danxuan"); cb.Checked = true; } } }
这样全选和全不选就做好了,
二 现在再做一个超连接
把其中一列改为
<asp:HyperLinkField DataTextField="OrderId" HeaderText="IP地址" DataNavigateUrlFormatString="WebForm1.aspx?HangBiaoShi={0}"
DataNavigateUrlFields="OrderId"
HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
Target="_self" >
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:HyperLinkField>
绑定字段是Orderid,DataNavigateUrlFormatString是超连接的地址,后面的参数是“DataNavigateUrlFields="OrderId”,这样我们点这一列就会定向到一个新的页面还会加一个参数。
当选中一列的时候,单机一个按键,得到这一列一个字段的值。
protected void Button2_Click(object sender, EventArgs e) { CheckBox cb; for (int i = 0; i <GridView1 .Rows.Count; i++) { cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("danxuan"); if (cb.Checked == true) { string ss = GridView1.Rows[i].Cells[1].Text; Response.Write(ss.ToString()); } } }
三,设置GridView的DataKeyNames属性,在这个属性里面,可以把我们后台绑定在GridView的字单全放在这个属性里面,用,号分开,可以放多个字单值,如:DataKeyNames="prizename,number,totalpointm,prizeid,
然后我们在后台如何使用呢?看下面:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//这行代码就可以得到我们当前在保存在页面DataKeyNames属性里的字单的值!而且它还会自动找到当前行的值,很不错哦!
String lsHBaseInfoId = GridView1.SelectedDataKey.Values["prizename"].ToString();
String id = GridView1.SelectedDataKey.Values["number"].ToString();
Response.Write(lsHBaseInfoId);
}
GridView1_SelectedIndexChanged这个事件的意思是:当你选择行时,对这行操作时发生,比如我们在GridView里面加了一个
<asp:CommandField SelectText="处理" HeaderText="操作" ShowSelectButton="True"/> 列,当我们在页面点击这列的时候就会
进入到这个方法!
---------------------------------------------------------------------
从GridView里面导出EXCEL文件:
#region 导出到EXCEL按钮事件
protected void btnToExcel_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count <= 0) return;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
GridView1.Page.EnableViewState = false;
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("酒店佣金对账调整表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8));
Response.ContentType = "application/ms-excel";
Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
this.GridView1.DataSource = GetDataList(); //绑定GridView
this.GridView1.DataBind();
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
GridView1.AllowPaging = true;
Response.End();
}
#endregion
一定要重写这个方法,不然会报错!
public override void VerifyRenderingInServerForm(Control control)
{
}
这样简单就可以实现把GridView转成EXCEL输出了!就这么简单!
//gvw 需要合并的GridView,sCol要合并开始列(从0开始),eCol要合并的结束列
public static void MergeRows(GridView gvw, int sCol, int eCol)
{
for (int rowIndex = gvw.Rows.Count - 2; rowIndex >= 0; rowIndex--)
{
GridViewRow row = gvw.Rows[rowIndex];
GridViewRow previousRow = gvw.Rows[rowIndex + 1];
for (int i = sCol; i < eCol + 1; i++)
{
if (row.Cells[i].Text != "" && row.Cells[i].Text != " ")
{
if (row.Cells[i].Text == previousRow.Cells[i].Text)
{
row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 1 ? 2 : previousRow.Cells[i].RowSpan + 1;
previousRow.Cells[i].Visible = false;
}
}
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GridR = GridView1.SelectedRow;
string S = GridR.Cells[1].Text.ToString();
Response.Write(S);
}
今天先写到这,过几天有时间再加一些别的用方法
http://www.360doc.com/content/12/0904/10/1039473_234182842.shtml