簡體   English   中英

如何將復選框添加到 GridView?

[英]How can I add Checkbox to 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>

我使用 c# 作為處理它

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

現在我需要檢查復選框chkProductonline取決於從產品列表中讀取如果product.on是 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM