Mark
Mark

Reputation: 315

ASP.NET C# Code button in gridview

Hi all I have a GridView (GridView1) I have added a column and insert a button:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
            AutoGenerateColumns="False" DataSourceID="ObjectDataSource2" 
            onselectedindexchanged="GridView1_SelectedIndexChanged" Width="798px">
            <Columns>
                .....
                <asp:ButtonField ButtonType="Button" CommandName="cmdFlag" Text="Flag" />
            </Columns>
        </asp:GridView>

Basically on click of the button I want to run a SQL Update but cant seem to click the button to enter C# and add the query. I can get in the C# for the page but unsure what to write for the method.

Heres the C# Code:

 void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmdFlag")
        {
        con.Open();

        cmd = new SqlCommand("UPDATE Comments SET Flagged = '" + "Yes" + "'", con); 

        cmd.ExecuteNonQuery();


        }

    }

Its doing nothing though. Basically I need it to look at the row and if the flagged button is clicked, update the comment to "Yes" under flagged.

Upvotes: 2

Views: 16557

Answers (4)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You have forgot to add OnRowCommand="GridView1_RowCommand" on your Gridview, that's why it is not firing the RowCommand Event.

<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AllowPaging="True" 
        AutoGenerateColumns="False" DataSourceID="ObjectDataSource2" 
        onselectedindexchanged="GridView1_SelectedIndexChanged" Width="798px">

Upvotes: 0

painotpi
painotpi

Reputation: 6996

Register the event-handler in your code-behind file by doing this

GridView1.RowCommand += new GridViewCommandEventHandler(GridView1_RowCommand);

and add this in you aspx page

OnRowCommand="GridView1_RowCommand"

Upvotes: 0

Ahmed Magdy
Ahmed Magdy

Reputation: 6050

If you want to add the ID to use it in your WHERE statement you can put it into CommandArgument like

<asp:ButtonField ButtonType="Button" CommandName="cmdFlag" Text="Flag" CommandArgument='<%# Eval("Comment_ID") %>' />

then in the code you can get it from

var id = e.CommandArgument.ToString();

Update: just updated the code

Upvotes: 0

Anuraj
Anuraj

Reputation: 19618

You won't get a direct event. You need to write code on the RowCommand event.

void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="cmdFlag")
        {
        //Write code update database
    }
}

Also you need to modify the GridView control. Add event like this.

onrowcommand="GridView1_RowCommand"

You can get more info here

Upvotes: 2

Related Questions