开发者

Why does findcontrol need unique id, when I have given it the row to scan

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 Ch开发者_开发问答eckBox();
         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.


Just append the row number to the ID:

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

And of course, append it to your FindControl parameter as well:

check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate" + i.ToString());


You added the checkbox to the cell, not the row:

table_cell2.Controls.Add(checkmate);

Hence - one row has multiple cells with id "checkmate":

E.g

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

So within the row "somerow", there are multiple checkboxes with id "checkmate".

Your code to add the checkboxes seemingly looks like you're only adding one though - so it must be something you've missed.

Try removing the FindControl code and see what actual HTML get's rendered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜