2016-07-02 133 views
1

如何获取复选框被选中如何获取复选框被选中

<asp:Table ID="mytbl" runat="server"> 
</asp:Table> 

while (res.Read()) 
{ 
    trow = new TableRow(); 
    tcell1 = new TableCell(); 
    tcell2 = new TableCell(); 
    CheckBox ch = new CheckBox(); 
    ch.CssClass = "chkBox"; 
    ch.ID = res.GetInt32(1) + "_" + res.GetInt32(2); 
    //ch. = res.GetInt32(1) + "_" + res.GetInt32(2); 
    values.Add(res.GetInt32(1) + "_" + res.GetInt32(2)); 
    tcell1.Controls.Add(ch); 
    tcell2.Text = res.GetString(0); 
    trow.Cells.Add(tcell1); 
    trow.Cells.Add(tcell2); 
    mytbl.Rows.Add(trow);  
} 

我想检查复选框被选中,并保存导致数据库

+0

http://i.imgur.com/4YJvHFH.jpg –

回答

0

什么我知道你想查看哪些复选框在表格中被检查过,然后根据你想对检查的记录进行一些操作。

所以要做到这一点,你可以循环看到复选框是否被选中。

HtmlTable table = (HtmlTable)Page.FindControl("mytbl"); 
foreach (HtmlTableRow row in table.Rows) 
{ 
    foreach (HtmlTableCell cell in row.Cells) 
    { 
     foreach (Control c in cell.Controls) 
     { 
      if (c is CheckBox && ((CheckBox)c).Checked) 
      { 
       //do some operation here 
      } 
     } 
    } 
} 

输出:

enter image description here

+0

错误:/ http://i.imgur.com/UrK4KSm.jpg –

+0

有你添加了'System.Web.UI.HtmlControls'引用和命名空间?看到错误正在清除,告诉你该怎么做。 –

+0

error table.rows http://i.imgur.com/2n8D24O.jpg –

0

看一看的例子below.I没有访问到你的数据库,所以我改变了我填充我这边的路表只是为了让它的工作,但是当你点击Save按钮逻辑通过表循环,让你评估复选框(如果它被选中与否)的:

后面的代码:

protected void Page_Load(object sender, EventArgs e) 
{ 
    TableRow row1 = this.CreateRow("checkBox1", "chkBox", "Row 1"); 
    TableRow row2 = this.CreateRow("checkBox2", "chkBox", "Row 2"); 

    mytbl.Rows.Add(row1); 
    mytbl.Rows.Add(row2); 
} 

private TableRow CreateRow(string id, string css, string text) 
{ 
    var row = new TableRow(); 
    var cell1 = new TableCell(); 
    var cell2 = new TableCell { Text = text }; 
    var checkBox = new CheckBox 
    { 
     CssClass = css, 
     ID = id 
    }; 
    cell1.Controls.Add(checkBox); 
    row.Cells.Add(cell1); 
    row.Cells.Add(cell2); 
    return row; 
} 

protected void btnSave_Click(object sender, EventArgs e) 
{ 
    foreach (TableRow row in mytbl.Rows) 
    { 
     CheckBox checkBox = row.Cells[0].Controls[0] as CheckBox; 
     string rowText = row.Cells[1].Text; 

     if(checkBox.Checked) 
     { 
      //Perform further processing 
     } 
    } 
} 

.ASPX:

<form runat="server"> 
    <asp:table id="mytbl" runat="server"></asp:table> 
    <asp:button id="btnSave" runat="server" text="Save" OnClick="btnSave_Click" /> 
</form> 
相关问题