1

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?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
daidai
  • 531
  • 5
  • 10
  • 22

3 Answers3

5

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.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
afzalulh
  • 7,925
  • 2
  • 26
  • 37
2

When it comes to gridviews that each row have an action (like edit button, or details), I personally like to do the following:

  1. Have a hidden button right after the GridView, this button has an onclick event (let's say OnDetailsButtonClick). So this button is the one that will be making the submission.
  2. Create a Hidden Field that will be filled when an action from a row is clicked, so that the server side code will pick up which rowId that the action was performed on
  3. Make every button in the gridview to have OnClientClick (lets say the javascript function called goToDetails(entityId)) so the javascript function will look like:
function goToDetails(entityId){
    $("#HiddenEntityId").val(entityId);
    $("#Button").click()
}

from the code behind you can get the row/Entity ID from the hidden field:

private void OnDetailsButton_Click(object sender, EventArgs e){
   string entityId = HiddenEntityId.Value;
   //now you can do whatever you like
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Saad Alothman
  • 353
  • 2
  • 10
0

You have to use 'Gridview.RowCommand' handle to enable custom script for a button in a ButtonField..

I.e.

1) add a 'CommandName' property to your buttonfield, this example assumes the CommandName = "Delete"

2)

    Protected Sub GridView1_buttonsclicked(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand

    If e.CommandName = "Delete" Then
        'Delete clicked with index of " + e.CommandArgument.ToString

        'Your code here, using the e.commandargument as the gridview index, then select column values using that index.

    End If

End Sub
Josh Harris
  • 446
  • 4
  • 8