我正在尝试创建一个表,它的行有文本框填充,并将它们保存在数据库中。为此,我需要将文本框的id分配给一个数组,并使用return this array作为保存按钮的单击事件,但出现了这个错误!有没有人帮我修一下?
private string[][] GenerateTable(int colsCount, int rowsCount)
{
string[][] controls_Array = new string[7][];
//Create the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
table.CellSpacing =5;
table.BorderWidth = 0;
Page.Form.Controls.Add(table);
TableColoumnHeader(table,table.Rows);
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
Label lbl = new Label();
lbl.Text = "row"+i.ToString();
///
TableCell TC = new TableCell();
TC.Controls.Add(lbl);
row.Cells.Add(TC);
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
// Add the control to the TableCell
if(j==colsCount-1)
{
CheckBox chkb = new CheckBox();
chkb.ID = "CheckBoxRow_" + i + "Cols_" + j;
cell.Controls.Add(chkb);
controls_Array[j][i] = chkb.ID;
}
else
{
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
controls_Array[j][i] = tb.ID;// this line where is the mentioned error occurred.
}
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}/**/
return controls_Array;
}发布于 2014-02-09 02:40:40
您的controls_Array仅针对第一个维度初始化为固定值(7)。
所以这就像你声明了7个数组,但是每个数组都没有维数。
当您尝试在第二维的第一个元素中插入一个值时,会得到空引用,因为该数组没有该维的大小。
您似乎想用行和列中的数据来填充它。
因此,修复代码的最简单方法是使用行和列正确地初始化数组
开始给出行的大小
string[][] controls_Array = new string[rowsCount][];在进入内部循环之前,对当前行[i]的列的数组进行维数
controls_Array[i] = new string[colsCount];
for (int j = 0; j < colsCount; j++)
{
.....
}另外,我认为当您在数组中插入项时,需要切换索引器,因为数组的第一维表示行(indexer i),而第二维表示列(indexer j)
controls_Array[i][j] = tb.ID;和
controls_Array[i][j] = chkb.ID;https://stackoverflow.com/questions/21649968
复制相似问题