首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >create TextBoxs表中出现类型为'System.NullReferenceException‘的异常

create TextBoxs表中出现类型为'System.NullReferenceException‘的异常
EN

Stack Overflow用户
提问于 2014-02-09 02:21:21
回答 1查看 569关注 0票数 0

我正在尝试创建一个表,它的行有文本框填充,并将它们保存在数据库中。为此,我需要将文本框的id分配给一个数组,并使用return this array作为保存按钮的单击事件,但出现了这个错误!有没有人帮我修一下?

代码语言:javascript
运行
复制
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;

}
EN

回答 1

Stack Overflow用户

发布于 2014-02-09 02:40:40

您的controls_Array仅针对第一个维度初始化为固定值(7)。

所以这就像你声明了7个数组,但是每个数组都没有维数。

当您尝试在第二维的第一个元素中插入一个值时,会得到空引用,因为该数组没有该维的大小。

您似乎想用行和列中的数据来填充它。

因此,修复代码的最简单方法是使用行和列正确地初始化数组

开始给出行的大小

代码语言:javascript
运行
复制
string[][] controls_Array = new string[rowsCount][];

在进入内部循环之前,对当前行[i]的列的数组进行维数

代码语言:javascript
运行
复制
controls_Array[i] = new string[colsCount];
for (int j = 0; j < colsCount; j++)
{
   .....
}

另外,我认为当您在数组中插入项时,需要切换索引器,因为数组的第一维表示行(indexer i),而第二维表示列(indexer j)

代码语言:javascript
运行
复制
controls_Array[i][j] = tb.ID;

代码语言:javascript
运行
复制
controls_Array[i][j] = chkb.ID;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21649968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档