本文介绍了我得到错误“索引超出范围。必须是非负数且小于集合的大小。参数名称:index"。。我会解决它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void BindGrid()
{
int selectedRowIndex = GridView1.SelectedIndex;
int pId = (int)GridView1.DataKeys[selectedRowIndex].Value;//I get error in this line.
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString =
ConfigurationManager.ConnectionStrings[
"ConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT ProductId, ProductName, Price FROM Product " +
"WHERE ProductId=@ProductId", conn);
comm.Parameters.Add("ProductId", SqlDbType.Int);
comm.Parameters["ProductId"].Value = pId;
try
{
conn.Open();
reader = comm.ExecuteReader();
employeeDetails.DataSource = reader;
employeeDetails.DataKeyNames = new string[] { "ProductId" };
employeeDetails.DataBind();
reader.Close();
}
finally
{
conn.Close();
}
}
推荐答案
GridView控件中所选行的从零开始的索引。 默认值为-1,表示当前没有选择行。
The zero-based index of the selected row in a GridView control. The default is -1, which indicates that no row is currently selected.
您可以这样修改代码:
You could modify your code this way:
private void BindGrid()
{
int selectedRowIndex = GridView1.SelectedIndex;
if ( selectedRowIndex < 0) return;
//...
}
}
这篇关于我得到错误“索引超出范围。必须是非负数且小于集合的大小。参数名称:index"。。我会解决它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!