使用按钮单击上的文本框填充网格视图中的数据 - 显示错误输入器超出范围

时间:2013-12-25 10:51:00

标签: asp.net

当我使用文本框插入数据时,它显示索引超出范围的错误

Button_Click()

    DataTable dt = new DataTable();
    DataRow dr;
    dt.Columns.Add("Name"); ///enter code here
    dt.Columns.Add("Address");
    dt.Columns.Add("Number");
    //First fill all the date present in the grid
    for (int intCnt = 0; intCnt < grd.Rows.Count; intCnt ++)
    {
    if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
    {
    dr = dt.NewRow();
    dr["Name"] = grd.Rows[intCnt].Cells[0].Value;/// at this point
    dr["Address"] = grd.Rows[intCnt].Cells[1].Value;
    dr["Number"] = grd.Rows[intCnt].Cells[2].Value;
    dt.Rows.Add(dr);
    }
    }
    dr = dt.NewRow();
    dr["Name"] = txt1.Text;
    dr["Address"] = txt2.Text;
    dr["Number"] = txt3.Text;
    dt.Rows.Add(dr);
    grd.DataSource = dt;
    grd.DataBind();
    }

2 个答案:

答案 0 :(得分:1)

试试这个

您必须在for循环中使用grd.Rows.Count-1

Button_Click()

DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Columns.Add("Number");

for (int intCnt = 0; intCnt < grd.Rows.Count-1; intCnt ++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Name"] = grd.Rows[intCnt].Cells[0].Value;/// at this point
dr["Address"] = grd.Rows[intCnt].Cells[1].Value;
dr["Number"] = grd.Rows[intCnt].Cells[2].Value;
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Name"] = txt1.Text;
dr["Address"] = txt2.Text;
dr["Number"] = txt3.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}

希望这能帮到你

答案 1 :(得分:0)

将for循环的条件更改为for (int intCnt = 0; intCnt < grd.Rows.Count-1; intCnt ++) {...}
而不是for (int intCnt = 0; intCnt < grd.Rows.Count; intCnt ++) {...}