sara adly
sara adly

Reputation: 297

How can I add Checkbox to GridView?

I have this 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

  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

how can I do that?

Upvotes: 1

Views: 308

Answers (1)

TheRotag
TheRotag

Reputation: 418

In your gvValues_RowDataBound method (in code behind), you can get the checkbox control and populate it from the current data item. 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;
    }
}

Upvotes: 1

Related Questions