我正在动态创建表和一些控件,因此在生成错误时:对象引用未设置为对象的实例。在“tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j+1];
”所以如何防止这种情况?
private void SetPreviousData(int rowsCount, int colsCount)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
for (int i = 0; i < rowsCount; i++)
{
//DropDownList drList = (DropDownList)table.Rows[i].Cells[0].FindControl("DropDownRow_" + i + "Col_" + i);
//drList.Text = Request.Form["DropDownRow_" + i + "Col_" + i];
for (int j = 0; j < colsCount-1; j++)
{
TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j+1);
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j+1];
string text = tb.Text;
string id = tb.ID;
}
}
}
}
private void GenerateTable(int rowsCount)
{
Table table = new Table();
TableHeaderRow header = new TableHeaderRow();
TableHeaderCell headerTableCell1 = new TableHeaderCell();
table.ID = "Table1";
Page.Form.Controls.Add(table);
const int colsCount = 4;
headerTableCell1.Text = "Item Name";
header.Cells.Add(headerTableCell1);
table.Rows.Add(header);
for (int i = 0; i < rowsCount; i++)
{
TableCell cell = new TableCell();
TableRow row = new TableRow();
DropDownList drList = new DropDownList();
drList.ID = "DropDownRow_" + i + "Col_" + i;
cell.Controls.Add(drList);
row.Cells.Add(cell);
for (int j = 1; j < colsCount; j++)
{
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
}
// Creating a header row
SetPreviousData(rowsCount, colsCount);
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}