找到了具有相同ID'的多个控件。 FindControl要求控件具有唯一ID

时间:2011-01-25 18:58:30

标签: asp.net gridview

更新

这是我观察到的:

if i get    org.Registrations.Count = 1 then 
    txtBox.ID   "_registration0_0"  string
....
....

如果我得到org.Registrations.Count = 2那么它的行为很奇怪

txtBox.ID   "_registration2_0"  
txtBox.ID   "_registration2_1"


after that i starts again with _registration2_0

ps:如果count = 1

,我没有问题

结束更新

错误消息清楚地表明我正在尝试重复ID,但下面是我创建动态文本框的地方,你看到我的代码中有什么错误吗?

protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
   Students org = (namespace.Students )(e.Row.DataItem);

   foreach (Registration reg in org.Registrations)
   {
      int _count = org.Registrations.Count;
      for (int rowId = 0; rowId < _count; rowId++)
      {
         TextBox txtBox = new TextBox();
         txtBox.ID = "_registration" + e.Row.RowIndex + "_" + rowId;
         txtBox.Text = reg.Name;
         e.Row.Cells[7].Controls.Add(txtBox);
     }
   }
}

2 个答案:

答案 0 :(得分:0)

似乎如果您有多个org.Registrations,您最终可能会遇到重复的ID。 看看下面的测试变量的用法:

protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
   Students org = (namespace.Students )(e.Row.DataItem);
   int test =0;
   foreach (Registration reg in org.Registrations)
   {
      test++;
      int _count = org.Registrations.Count;
      for (int rowId = 0; rowId < _count; rowId++)
      {
         TextBox txtBox = new TextBox();
         txtBox.ID = "_registration" + e.Row.RowIndex + "_" + rowId + "_" + test.ToString();
         txtBox.Text = reg.Name;
         e.Row.Cells[7].Controls.Add(txtBox);
     }
   }
}

答案 1 :(得分:0)

我不需要for内的foreach循环..它按预期工作......这就是为什么要执行两次。

foreach (Registration reg in org.Registrations) 
{
   //
}