Ozan Manav Ozan Manav - 1 year ago 61
SQL Question

Gridview execute query with custom button

I have a Database and GridView in Asp.net Like this
My Gridview
I want to change OnayID value 0 to 1 when i click Onayla Button and i wrote some codes but im giving error i dont know why how can i fix it ? i tried some ways but i failure.

<asp:Button ID="Button1" runat="server" Text="Onayla" CommandName="OnaylaKomutu" />


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());
SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID='1' WHERE UserID = @" + UserID, con);


Answer Source

Looks like you are not handling the custom error properly. And there seem to some error in your code(let's see about that error later). And to make this go away, add the line below under <system.web> tag of your web.config

<customErrors mode="Off" defaultRedirect=""/>


<customErrors mode="Off"/>


string UserID = GridView1.SelectedRow.Cells[7].Text;//  This  is wrong in RowCommand Event

Instead use thie

int index = Convert.ToInt32(e.CommandArgument);
string UserID = GridView1.Rows[index].Cells[9].Text;

And Add command argument to Onayla Button in the TemplateField.

        <asp:Button ID="Button1" runat="server" Text="Onayla" CommandName="OnaylaKomutu" CommandArgument='<%#DataBinder.Eval(Container, "RowIndex")%>' />

Looks like there are lots of error. Here

SqlCommand cmd = new SqlCommand("UPDATE elmacustomers SET OnayID=1 WHERE UserID = " + UserID, con); //remove @ & single quote(')
cmd.ExecuteNonQuery(); //forgot to execute the command
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download