简体   繁体   English

如何将复选框添加到 GridView?

[英]How can I add Checkbox to GridView?

I have this Gridview我有这个 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>

I handle it using c# as我使用 c# 作为处理它

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

Now I need to check checkbox chkProductonline depending on reading from Products list if product.on is 1 check the check box现在我需要检查复选框chkProductonline取决于从产品列表中读取如果product.on是 1 检查复选框

how can I do that?我怎样才能做到这一点?

In your gvValues_RowDataBound method (in code behind), you can get the checkbox control and populate it from the current data item.在您的 gvValues_RowDataBound 方法(在后面的代码中)中,您可以获得复选框控件并从当前数据项填充它。 It's generally a good idea to check the current row type to make sure you're not in a header row, footer row, etc. since you only want to do this for actual item rows.检查当前行类型以确保您不在标题行、页脚行等中通常是一个好主意,因为您只想对实际项目行执行此操作。 It would look something like this:它看起来像这样:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM