我正在尝试更新gridview值,但我收到错误说:
System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。
我想获取选择进行编辑的第I行的值,以更新数据库中的值,并在gridView中显示已编辑的值。
以下是我的代码。
.aspx file
<asp:GridView ID="GridView1" DataKeyNames="ID" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:BoundField DataField="UserID" HeaderText="UserID" DataFormatString="{0:0.##}" />
<asp:BoundField DataField="UserKey" HeaderText="UserKey" DataFormatString="{0:0.##}" />
<asp:BoundField DataField="Value" HeaderText="Value" DataFormatString="{0:0.##}" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:SqlDataSource ID="updateQuery" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [ID], [UserID], [UserKey], [Value] FROM [FirstTable]"></asp:SqlDataSource>
.aspx.cs file:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
try
{
String UserID = (GridView1.Rows[e.RowIndex].Cells[1].Controls[0] as TextBox).Text;
Response.Write(UserID);
string updateSQL;
updateSQL = "UPDATE FirstTable SET UserID = @UserID, UserKey = @UserKey, Value = @Value WHERE ID = @ID";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(updateSQL, con);
cmd.Parameters.AddWithValue("@ID", ID);
cmd.Parameters.AddWithValue("@UserID", "aaa");
cmd.Parameters.AddWithValue("@UserKey", "bbb");
cmd.Parameters.AddWithValue("@Value", "ccc");
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
finally
{
con.Close();
}
GridView1.EditIndex = -1;
// GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
BindData();
}
catch(Exception er)
{
Response.Write(er);
}
}
答案 0 :(得分:1)
问题是您正在访问错误的列 前2个单元格有编辑按钮和删除按钮,第3个单元格有ID,所以你的userID在第4个单元格中。所以你必须访问那个单元格
String UserID = (GridView1.Rows[e.RowIndex].Cells[3].Controls[0] as TextBox).Text;