gpt4 book ai didi

c# - Gridview 中的索引超出范围错误

转载 作者:行者123 更新时间:2023-11-30 14:40:22 26 4
gpt4 key购买 nike

我在我的 Gridview 中添加了所有行 CheckBox 以帮助解决此问题 article .

这是我的计算按钮代码;

protected void Calculate_Click(object sender, EventArgs e)
{
bool atLeastOneRowDeleted = false;

foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
Response.Write(string.Format( "This would have deleted ProductID {0}<br />", productID));
}
}

}

但是当我这样做时,会出现这样的奇怪错误;

enter image description here

我该如何解决这个问题?

最好的问候,桑纳

最佳答案

确保您在 GridView 定义中定义了 DataKeys

  <asp:gridview id="GridView2" 
datakeynames="productID"
...
...>
enter code here

</asp:gridview>

也尝试像这样为 DataRow 添加检查

    foreach (GridViewRow row in GridView1.Rows) 
{
if(row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
if (cb != null && cb.Checked)
{
atLeastOneRowDeleted = true;
int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
Response.Write(string.Format( "This would have deleted ProductID {0}<br />", productID));
}
}
}

关于c# - Gridview 中的索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5381670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com