2012-03-29 44 views
0

海蘭所有,得到複選框選中的值,並把它放在一個行的表

我正在開發一個web應用程序,我試圖用一個CheckBoxList的。我希望對於該複選框列表中的每個選定項目在表格中創建一個新行。因此,如果我有5個項目,並且我選中3,我想要一個表格顯示3行,並在每行中顯示所選項目。這就是我得到什麼項目檢查:

protected void Button1_Click(object sender, EventArgs e) 
    { 
     string str = string.Empty; 

     foreach (ListItem item in check.Items) 
     { 
      str += item.Value; 
     } 
    } 

我的問題是:如何創建一個表與選定的值?我在一個asp.net應用程序中使用c#

回答

2

您需要在每次回發中重新創建此表,因爲它是動態創建的。

http://weblogs.asp.net/infinitiesloop/archive/2006/08/30/TRULY-Understanding-Dynamic-Controls-_2800_Part-3_2900_.aspx

這裏的工作示例代碼:

<asp:CheckBoxList ID="check" runat="server"> 
    <asp:ListItem Text="Item 1" Value="1"></asp:ListItem> 
    <asp:ListItem Text="Item 2" Value="2"></asp:ListItem> 
    <asp:ListItem Text="Item 3" Value="3"></asp:ListItem> 
</asp:CheckBoxList> 
<asp:Button ID="Button1" runat="server" Text="Apply Selection" OnClick="Button1_Click" /> 
<asp:Table ID="TblCheck" runat="server"></asp:Table> 

代碼隱藏:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (IsPostBack) RecreateTable(); 
} 

private void RecreateTable() 
{ 
    var selected = this.check.Items.Cast<ListItem>().Where(i => i.Selected); 
    foreach (var item in selected) 
    { 
     TableRow row = new TableRow(); 
     TableCell cell = new TableCell(); 
     Label lbl = new Label(); 
     lbl.Text = item.Text; 
     cell.Controls.Add(lbl); 
     row.Cells.Add(cell); 
     this.TblCheck.Rows.Add(row); 
    } 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    //RecreateTable(); 
} 

按鈕單擊處理程序不必當它從Page_Load中創建反正甚至創建它。

相關問題