tags:

views:

1539

answers:

3

When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event?

Thanks.

A: 

This article on the MSDN site clearly explains how to go about adding a button into a datagrid. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set.

This article shows how to use the command event with buttons. In it you use CommandArguments and CommandNames.

Brendan Enrick
A: 

Here is where I create the datagrid:

System.Web.UI.WebControls.DataGrid Datagridtest = new System.Web.UI.WebControls.DataGrid();

        Datagridtest.Width = 600;
        Datagridtest.GridLines = GridLines.Both;
        Datagridtest.CellPadding = 1;

        ButtonColumn bc = new ButtonColumn();
        bc.CommandName = "add";
        bc.HeaderText = "Event Details";
        bc.Text = "Details";
        bc.ButtonType = System.Web.UI.WebControls.ButtonColumnType.PushButton;
        Datagridtest.Columns.Add(bc);
        PlaceHolder1.Controls.Add(Datagridtest);

        Datagridtest.DataSource = dt;
        Datagridtest.DataBind();

And here is the event I am trying to use:

protected void Datagridtest_ItemCommand(object source, DataGridCommandEventArgs e) { .... }

Thought that might help because I can't seem to capture the event at all.

Collin Estes
+3  A: 
protected void Page_Load(object sender, EventArgs e)
{
  DataGrid dg = new DataGrid();

  dg.GridLines = GridLines.Both;

  ButtonColumn bc = new ButtonColumn();
  bc.CommandName = "add";
  bc.HeaderText = "Event Details";
  bc.Text = "Details";
  bc.ButtonType = ButtonColumnType.PushButton;
  dg.Columns.Add(bc);

  dg.DataSource = getDataTable();
  dg.DataBind();

  dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);

  pnlMain.Controls.Add(dg);
}

protected void dg_ItemCommand(object source, DataGridCommandEventArgs e)
{
  if (e.CommandName == "add")
  {
    throw new Exception("add it!");
  }
}

protected DataTable getDataTable()
{
  // returns your data table
}
Travis Johnson