我正在尝试从网格视图中删除记录但无法删除。 使用模板字段中的链接按钮从gridview中删除记录时,会出现这样的错误。
var id = GvTestimony.DataKeys[gvRow.RowIndex].Value.ToString();
错误信息在这里:
指数超出范围。必须是非负数且小于集合的大小。
参数名称:index
void TestimoniesGrid()
{
using (var sqlConnection = new SqlConnection(_conn))
{
using (var sqlCommand = new SqlCommand("SP_TestimoniesGridData", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
var dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count == 0)
{
GvTestimony.EmptyDataText = "This table has no data.";
}
else
{
GvTestimony.DataSource = dataTable;
GvTestimony.DataBind();
}
}
}
}
}
protected void lnkReject_OnClick(object sender, EventArgs e)
{
var linkButton = sender as LinkButton;
if (linkButton != null)
{
var gvRow = linkButton.NamingContainer as GridViewRow;
var id = GvTestimony.DataKeys[gvRow.RowIndex].Value.ToString();
using (var sqlConnection = new SqlConnection(_conn))
{
using (var sqlCommand = new SqlCommand("SP_DeleteTestimonyById", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@OwnStoryId", id);
sqlConnection.Open();
var result = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
if (result == 1)
{
TestimoniesGrid();
}
}
}
}
}
答案 0 :(得分:-1)
(对不起,这是我的第一个回答)看看你如何定义网格列以及你使用的是哪个版本的.NET,这很有趣。
在这里你可以找到一个带按钮的例子:
http://weblogs.asp.net/gurusarkar/get-gridview-rowindex-upon-button-click
我要复制最重要的部分,你可以用两种不同的方式来做:
在RowCommand事件上获取GridView行和GridView行索引
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
在TemplateField的Click事件中单击事件获取GridView行和GridView行索引
protected void Button1_Click(object sender, EventArgs e)
{
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
}
如果您需要更多信息,请告诉我们。
更多例子: