views:

258

answers:

2
+1  A: 

I would recommend you to use JQuery to add event handlers on your buttons. Here is a sample:


function onclick () {
  alert("1");
}
$(function () {
  $("input[type='submit']").click(onclick);
});

This code will attach the onclick function to the onclick event for all input elements of type submit when the DOM is ready.

The unobtrusive JavaScript technique may interest you.

I would like to mention that Microsoft supports JQuery, and they will make support for it in upcoming versions of Visual Studio. For more information please visit http://live.visitmix.com/.

knut
+2  A: 

MS has a standard implementation of bound fields, which does not set ID or attributes for ButtonColumn created buttons.

To be a bit more specific, whenever a grid creates cells and sub-sequentially buttons, it calls InitializeCell:

public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType)
{
 base.InitializeCell(cell, columnIndex, itemType);
 if ((itemType != ListItemType.Header) && (itemType != ListItemType.Footer))
 {
  WebControl child = null;
  if (this.ButtonType == ButtonColumnType.LinkButton)
   ...
  else
  {
   child = new Button {
    Text = this.Text,
    CommandName = this.CommandName,
    CausesValidation = this.CausesValidation,
    ValidationGroup = this.ValidationGroup
   };
  }
  ...
  cell.Controls.Add(child);
 }
}

As you can see, that's all there is to a button.

If you want it to have IDs and "onclick" attributes, you could use something like this:

protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  //assuming that a first cell is a ButtonField
  //note that in edit mode a button may be at some other index that 0
  Button btn = e.Row.Cells[0].Controls[0] as Button;
  if (btn != null)
  {
   btn.OnClientClick = "return confirm('are you sure?')";
   btn.ID = "myButtonX";
  }
 }
}
Ruslan