C# GridView详解
[*]前台代码
<!--id用于绑定数据的标识,--> <asp:GridView ID="gvLog" runat="server" AutoGenerateColumns="False" CellPadding="3" CellSpacing="1" Width="100%" BackColor="#F3F3F3" BorderWidth="0px" OnRowDeleting="gvLog_RowDeleting" OnRowDataBound="gvLog_RowDataBound"> <RowStyle BackColor="White" /> <Columns> <!--绑定列--> <asp:BoundField DataField="OperId" > <ItemStyle CssClass="display:none;" /> </asp:BoundField> <asp:BoundField HeaderText="No"> <ItemStyle Width="30px" HorizontalAlign="Center" /> </asp:BoundField> <!--带链接的绑定列,DataNavigateUrlFields表示要传递的参数,多个参数用逗号分割开--> <asp:HyperLinkField DataNavigateUrlFields="OperId,operName" DataNavigateUrlFormatString="OperatorEdit.aspx?OperId={0}&operName={1}" DataTextField="OperName" HeaderText="登录名称" > <ItemStyle Width="100px" /> </asp:HyperLinkField> <asp:BoundField HeaderText="真实名称" DataField="TrueName"> <ItemStyle Width="100px" /> </asp:BoundField> <asp:BoundField HeaderText="备注" DataField="OperMemo" /> <asp:HyperLinkField HeaderText="授权" NavigateUrl="OperatorRole.aspx" Text="角色授权" DataNavigateUrlFields="OperId" DataNavigateUrlFormatString="OperatorRole.aspx?operId={0}"> <ItemStyle Width="60px" HorizontalAlign="Center" /> </asp:HyperLinkField> <!--事件绑定操作,该例子是删除时间--> <asp:CommandField HeaderText="操作" ShowDeleteButton="True"> <ItemStyle Width="40px" HorizontalAlign="Center" /> </asp:CommandField> </Columns> <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" /> <!--表格头部样式--> <HeaderStyle BackColor="#CCCCCC" Font-Bold="True" ForeColor="#FFFEEE" Height="15px" /> <!--隔行变色--> <AlternatingRowStyle BackColor="#F9F9F9" /> </asp:GridView>
[*]后台代码---绑定gridview
DataSet ds = operServices.GetList(""); DataView dv = new DataView(ds.Tables); ///获取或设置用于筛选在 DataView 中查看哪些行的表达式。 dv.RowFilter = "isdel=0"; this.gvLog.DataSource = dv; this.gvLog.DataBind();
注1:DataView 使您能够创建 DataTable 中所存储的数据的不同视图,这种功能通常用于数据绑定应用程序。使用 DataView,您可以使用不同排序顺序显示表中的数据,并且可以按行状态或基于筛选器表达式来筛选数据。
注2:如果获取不到GridView隐藏控件的值,则需要加入以下一段代码
///该方法名称应该与你绑定的时间名称一致 protected void gvLog_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header) { ///指定隐藏列,并赋值 e.Row.Cells.Visible = false; e.Row.Cells.Visible = false; } }
注3:如果我们要根据某个条件去改变表格某个值的样式,可以在行绑定时间方法中加入如下代码,如:
protected void gvLog_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex != -1) { if (Convert.ToInt16(e.Row.Cells.Text.ToString()) == 1) { e.Row.Cells.Text = "<font color='red'><b>" + e.Row.Cells.Text.ToString() + "</b></font>"; } }}
页:
[1]