指定的参数超出了有效值的范围.参数名称:动态生成控件上的索引



我正在页面加载上创建动态复选框和文本框控件,我想在点击按钮时获得控件的值,但我们无法找到

这是我的动态控制代码

DataTable dt = new DataTable();
da.Fill(dt);
var Count = dt.Rows.Count;
if (Count > 0)
{

TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell cellheader = new TableHeaderCell();
TableHeaderCell thc = new TableHeaderCell();
TableHeaderCell thcode = new TableHeaderCell();
TableHeaderCell thcReason = new TableHeaderCell();
thc.Text = "Select";
thc.CssClass = "pd";
thcode.Text = "Description";
thcode.CssClass = "pdlbl";
thcReason.Text = "Reason";
thcReason.CssClass = "thcReason";
thr.Cells.Add(thc);
thr.Cells.Add(thcode);
thr.Cells.Add(thcReason);
tbl.Rows.Add(thr);
for (int i = 0; i < Count; i++)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
CheckBox chk = new CheckBox();
Label lbl = new Label();
TextBox txtBox = new TextBox();
txtBox.ID = "txt" + i.ToString();
txtBox.TextMode = TextBoxMode.MultiLine;
chk.ID = "chk" + i.ToString();
lbl.ID = "lbl" + i.ToString();
lbl.Text = dt.Rows[i]["DESCRIPTION"].ToString();
tc.Controls.Add(chk);
tc.Width = new Unit("5px");
tc.CssClass = "chkcntrl";
tc1.Controls.Add(lbl);
tc1.Width = new Unit("75%");
tc2.Controls.Add(txtBox);
tc2.Width = new Unit("20%");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tbl.Rows.Add(tr);
}
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}

创建控件后,我想找出的值

我的代码低于

foreach (TableRow tr in tbl.Controls)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
if (tc.Controls[1] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
if (tc.Controls[2] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}

}

但是当我执行这个代码时,我们得到了Specified argument was out of the range of valid values. Parameter name: index,请任何人都能告诉我错在哪里

添加的每个控件都有不同的表单元格。

tc有复选框控件tc1具有标签控制

编辑:您的代码还需要一些其他更改。

  1. 你一直在迭代,tbl。控件不是tbl。行
  2. 您正在遍历tr.Controls而不是tr.Cells
  3. 添加的第一个表行是没有控件因此添加了检查controls.count()是否大于0

希望这能帮助

foreach (TableRow tr in tbl.Rows)
{
string str_Confirmed = string.Empty;
string str_Description = string.Empty;
string str_Reason = string.Empty;
foreach (TableCell tc in tr.Cells)
{
if (tc.Controls.Count > 0)
{
if (tc.Controls[0] is CheckBox)
{
if (((CheckBox)tc.Controls[0]).Checked == true)
{
str_Confirmed = "Y";
}
else
{
str_Confirmed = "N";
}
}
else if (tc.Controls[0] is Label)
{
string txt = string.Empty;
str_Description = ((Label)tc.Controls[1]).Text;
}
else if (tc.Controls[0] is TextBox)
{
str_Reason = ((TextBox)tc.Controls[2]).Text;
//Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
}
}

最新更新