0

The code

    public partial class Table_Traversing : System.Web.UI.Page
        {
        Table table1 = new Table();

        Button button1 = new Button();

        protected void Page_Load(object sender, EventArgs e)
        {
            for (int adding_rows = 0; adding_rows < 4; adding_rows++)
               {
               TableRow table_row1 = new TableRow();
               TableCell table_cell1 = new TableCell();
               TableCell table_cell2 = new TableCell();
               Label The_text = new Label();
               CheckBox checkmate = new CheckBox();
               The_text.Text = "This is the text :-)";
               checkmate.ID = "checkmate";
               table_cell2.Controls.Add(checkmate);
               table_cell1.Controls.Add(The_text);
               table_row1.Controls.AddAt(0, table_cell1);
               table_row1.Controls.AddAt(1, table_cell2);
               table1.Rows.Add(table_row1);
               }
            button1.Text = "click me to export the value";
            form1.Controls.AddAt(0, table1);
            form1.Controls.AddAt(1, button1);
            button1.Click += new EventHandler(button1_Click);     
        }

        void button1_Click(object sender, EventArgs e)
        {
        CheckBox check_or_not = new CheckBox();
         for (int i = 0; i < table1.Rows.Count; i++)
            {
             check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate");
             Response.Write(check_or_not.Checked.ToString());
             }       
         }
      }

The error

Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs.

4

2 回答 2

2

只需将行号附加到 ID:

checkmate.ID = "checkmate" + adding_rows.ToString();

当然,也将它附加到您的 FindControl 参数中:

check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate" + i.ToString());
于 2010-09-04T05:39:00.550 回答
0

您将复选框添加到单元格,而不是行:

table_cell2.Controls.Add(checkmate);

因此 - 一行有多个 ID 为“将死”的单元格:

例如

<tr id="somerow">
   <td><input type="checkbox" id="checkmate"/></td>
   <td><input type="checkbox" id="checkmate"/></td>
</tr>

因此,在“somerow”行中,有多个 id 为“checkmate”的复选框。

您添加复选框的代码看起来好像您只添加了一个 - 所以它一定是您错过的东西。

尝试删除 FindControl 代码并查看实际呈现的 HTML 内容。

于 2010-09-04T05:32:58.800 回答