使用文本框绑定网格视图

时间:2014-10-06 07:27:08

标签: c# asp.net gridview

在下面的代码中我有一个会话值,我必须传递给网格并绑定值。网格由文本框组成,如果会话值为2,应该有两行textbox。我试过它抛出索引超出了范围。请帮我解决这个问题。

int GoodsReceivedNoteID = (int)Session["GoodsReceivedNoteID"];
for (int iRow = 0; iRow < GoodsReceivedNoteID; iRow++)
{
    TextBox txtFreightCharges = (TextBox)gvGRN.Rows[iRow].Cells[6].FindControl("txtFreightCharges");
    TextBox txtLoadingCost = (TextBox)gvGRN.Rows[iRow].Cells[6].FindControl("txtLoadingCost");
    TextBox txtUnloadingCost = (TextBox)gvGRN.Rows[iRow].Cells[6].FindControl("txtUnloadingCost");
    TextBox txtInsuranseCost = (TextBox)gvGRN.Rows[iRow].Cells[6].FindControl("txtInsuranseCost");
    TextBox txtOtherExpenses = (TextBox)gvGRN.Rows[iRow].Cells[6].FindControl("txtOtherExpenses");
}

1 个答案:

答案 0 :(得分:1)

不要使用Rows[index].Cells[6].FindControl,该单元格不是NamingContainer的TemplateField中控件的GridViewRow,而是行本身。我也不了解会话值与网格中行数之间的关系。这更简单,更易读:

foreach(GridViewRow row in gvGRN.Rows)
{
    TextBox txtFreightCharges = (TextBox)row.FindControl("txtFreightCharges");
    TextBox txtLoadingCost = (TextBox)row.FindControl("txtLoadingCost");
    TextBox txtUnloadingCost = (TextBox)row.FindControl("txtUnloadingCost");
    TextBox txtInsuranseCost = (TextBox)row.FindControl("txtInsuranseCost");
    TextBox txtOtherExpenses = (TextBox)row.FindControl("txtOtherExpenses");
}

如果你只想要GoodsReceivedNoteID - 行(由于ID不是计数器,这听起来不对):

for(int i = 0; i < GoodsReceivedNoteID; i++))
{
    GridViewRow row = gvGRN.Rows[i];
    TextBox txtFreightCharges = (TextBox)row.FindControl("txtFreightCharges");
    // ...
}