如何将Checkbox添加到GridView?

时间:2016-04-05 15:25:27

标签: javascript c# jquery asp.net asp.net-mvc

我有这个Gridview

  <asp:GridView ID="gvValues" runat="server" Width="100%" AllowPaging="True" PagerSettings-Mode="NumericFirstLast" OnRowCommand="gvValues_RowCommand"
 AutoGenerateColumns="False" CellPadding="0" PageSize="15" ItemType="Product" CssClass="table-striped table-condensed table table-bordered table-hover"
  OnRowDataBound="gvValues_RowDataBound" OnPageIndexChanging="gvValues_PageIndexChanging" meta:resourcekey="gvValuesResource1" EmptyDataText="No Products in your Pos">
 <EmptyDataRowStyle Font-Bold="True" Font-Size="16pt" ForeColor="Red" />
      <RowStyle Wrap="true" HorizontalAlign="Center" />
      <Columns>
         <asp:TemplateField HeaderText="#">
            <ItemTemplate><%# gvValues.PageSize*gvValues.PageIndex+ Container.DisplayIndex+1  %> 
               <asp:CheckBox ID="chkProduct" runat="server" CssClass="chkProduct"/>
                  </ItemTemplate>
               </asp:TemplateField>
              <asp:TemplateField  HeaderText="online" meta:resourcekey="Online">
         <ItemTemplate > 
              <asp:CheckBox ID="chkProductonline" runat="server"  />
          </ItemTemplate>
           </asp:TemplateField>
        </Columns>
  </asp:GridView>

我用c#处理它 如

  products = GetProduct();    
  gvValues.DataSource = products;
  gvValues.DataBind();

现在我需要选中复选框chkProductonline,具体取决于在product.on为1时从产品列表中读取,请选中复选框

我该怎么做?

1 个答案:

答案 0 :(得分:1)

在你的gvValues_RowDataBound方法中(在后面的代码中),你可以获得复选框控件并从当前数据项中填充它。检查当前行类型通常是个好主意,以确保您不在标题行,页脚行等中,因为您只想对实际项目行执行此操作。它看起来像这样:

private void gvValues_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Make sure current row is a data row (not header, footer, etc.)
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // Get checkbox control
       var chkProductonline= e.Row.FindControl("chkProductonline") as CheckBox;

       // Get data item (recommend adding some error checking here to make sure it's really a Product)
       var product = e.Row.DataItem as Product

       // Set checkbox checked attribute
       chkProductonline.Checked = product.on;
    }
}