我在Asp.net中有一个数据库和GridView就像这样 My Gridview 我想将OnayID值0更改为1,当我点击Onayla Button并且我写了一些代码但是我给出了错误我不知道为什么我该如何解决它?我尝试了一些方法,但我失败了。
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Onayla" CommandName="OnaylaKomutu" />
</ItemTemplate>
</asp:TemplateField>
CODEBEHIND:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "OnaylaKomutu")
{
string UserID = GridView1.SelectedRow.Cells[7].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ElmaCafeDBConnectionString"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID='1' WHERE UserID = @" + UserID, con);
con.Close();
}
}
答案 0 :(得分:0)
看起来您没有正确处理自定义错误。并且您的代码中似乎存在一些错误(稍后我们会看到该错误)。要使其消失,请在<system.web>
web.config
标记下添加以下行
<customErrors mode="Off" defaultRedirect=""/>
OR
<customErrors mode="Off"/>
<强>更新强>
string UserID = GridView1.SelectedRow.Cells[7].Text;// This is wrong in RowCommand Event
而是使用
int index = Convert.ToInt32(e.CommandArgument);
string UserID = GridView1.Rows[index].Cells[9].Text;
和
将命令参数添加到Onayla
中的TemplateField
按钮。
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Onayla" CommandName="OnaylaKomutu" CommandArgument='<%#DataBinder.Eval(Container, "RowIndex")%>' />
</ItemTemplate>
</asp:TemplateField>
看起来有很多错误。这里
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID=1 WHERE UserID = " + UserID, con); //remove @ & single quote(')
cmd.ExecuteNonQuery(); //forgot to execute the command
答案 1 :(得分:0)
错误来自以下行。
string UserID = GridView1.SelectedRow.Cells[7].Text;
//GridView1.SelectedRow == null
从RowIndex
对象计算GridViewCommandEventArgs
并不容易。更好的是将CommandArgument='<%#Eval("UserID")%>'
添加到<asp:Button ... />
。那你就有了
string UserID = e.CommandArgument;
当您修复第一个错误时,您将遇到另一个问题
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID='1' WHERE UserID = @" + UserID, con); //in effect "...where UserID = @123"
有效代码可能如下所示。
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID='1' WHERE UserID = @UserID", con);
cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = UserID;
cmd.ExecuteNonQuery(); //You forget to execute
答案 2 :(得分:0)
感谢您的回答。我解决了你的问题。 @jonju 在这里回答: ASP.NET
<asp:Button ID="Button1" runat="server" Text="Onayla" OnClick="OnaylaButton_Click"/>
C#
protected void OnaylaButton_Click(object sender, EventArgs e)
{
int index = GridView1.SelectedRow.DataItemIndex;
string UserID = GridView1.Rows[index].Cells[3].Text;
Label2.Text = UserID;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ElmaCafeDBConnectionString"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID=1 WHERE UserID =' " + UserID + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
Label_Uyarı.Visible = false;
}