How to make click event for button field in grid view asp.net

daidai picture daidai · Sep 14, 2013 · Viewed 31.3k times · Source

I have dynamically created GridView in my .aspx from codebehind. I inserted a sql table in that GridView. Then I added one more button filed column. Here is the code:

ButtonField bf = new ButtonField();
bf.Text = "Details";
bf.ButtonType = ButtonType.Button;

DataTable table = new DataTable();
table.Load(reader);
GridView gv = new GridView();
gv.Columns.Add(bf);
gv.DataSource = table;
gv.DataBind();

Now I want to add a MouseClickEvent on this ButtonField, but there is no property Click or MouseClick. Is there any way to do this?

Answer

afzalulh picture afzalulh · Sep 14, 2013

For a ButtonField inside GridView you specify CommandName:

bf.CommandName = "MyCommand";

And access it like:

void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "MyCommand")
    {
    }
}

You may find it useful: ButtonField.CommandName Property.