如何动态创建自定义控件?

时间:2013-01-22 10:13:40

标签: asp.net gridview checkbox

让我直截了当。我设法使用单个Gridview创建自定义checkbox,但我的问题是我想要包含多个动态Checkbox

这是我的代码:

<%@ Control Language="C#" AutoEventWireup="true" EnableTheming="true" CodeFile="GridviewControl.ascx.cs" Inherits="UserControl_GridviewControl" %>

<link href="../Template/CSS/Style.css"type="text/css" rel="Stylesheet" />

<div>
  <span id="Span5" style="font-family: Arial; font-size:12px;" ><asp:Label ID="lblCount" runat="server" Text="0" Font-Bold="true"></asp:Label>
                     Record/s</span>
  <span class="maintenance-btns">
     <asp:Button ID="btnNew" runat="server" Text=" New " onclick="btnNew_Click"/>
     <asp:Button ID="btnDel" runat="server" Text=" Delete " onclick="btnDel_Click"/>
  </span>
</div>

<asp:Panel ID="pnlPc" runat="server" CssClass="div-grid" ScrollBars="Auto">  
<asp:GridView ID="gvListing" runat="server" AllowPaging="True" AutoGenerateSelectButton="true"
            OnRowDataBound="gvListing_RowDataBound" skinid="gvListing"
            onselectedindexchanged="gvListing_SelectedIndexChanged"
            onpageindexchanging="gvListing_PageIndexChanging" PageSize="50" >

<FooterStyle CssClass="grid-footer" />

<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true" 
OnCheckedChanged="chkSelectAll_CheckedChanged" CssClass="select-all"/>
</HeaderTemplate>

<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" 
OnCheckedChanged="chkSelect_CheckedChanged" CssClass="listing-checkbox"/>
</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>
</asp:Panel>

在此gridview中,我在第一列只有checkboxes。我想将动态生成的checkboxes放在最后一列。

P.S。:如何使用动态创建checkboxes

来检索ID

1 个答案:

答案 0 :(得分:1)

你可以这样做

  protected void gvData_DataBound(object sender, EventArgs e) 
  {
    foreach (GridViewRow objRow in gvData.Rows)
    {
      TableCell tcCheckCell = new TableCell();
      var checkBox = new CheckBox();
      checkBox.CheckedChanged += checkBox_CheckedChanged;
      tcCheckCell.Controls.Add(checkBox);
      objRow.Cells.AddAt(0, tcCheckCell);
   }
  }
 void checkBox_CheckedChanged(object sender, EventArgs e)
 {
    //do something
 }