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?

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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
}

1 Comment

How do you pass the entityId to the goToDetails function?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.