简体   繁体   中英

How to create button in dynamically created Gridview?

I'm using AJAX Control Toolkit to create Tabpanels . Each panel is populated with a gridview as per below code.

Now, I want to add one button per each row. When it is clicked it should pass as parameter one of the cells of that row, but as the Gridview is dynamically created, I don't know how. Any tips?

foreach (DataTable dt in DataSet1.Tables)
{
    GridView gv = new GridView();
    var thepanel = new AjaxControlToolkit.TabPanel();
    gv.DataSource = dt;
    gv.DataBind();
    thepanel.Controls.Add(gv);
    TabContainer.Controls.Add(thepanel);
}

您可以添加一个选择按钮,网格如下:

Gridview1.AutoGenerateSelectButton=true;

I just found a solution for whom this may interest:

First, you should include fllwg lines BEFOREthe databind:

gv.RowDataBound += gv_RowDataBound;
gv.RowCommand += gv_RowCommand;

Then define the RowDataBound to insert the Linkbutton:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            LinkButton butIgnorar = new LinkButton()
            {
               CommandName = "Ignorar",
               ID = "butIgnorar",
               Text = "Ignorar",
               //optional: passes contents of cell 1 as parameter
               CommandArgument =  e.Row.Cells[1].Text.ToString()
            };
            //Optional: to include some javascript cofirmation on the action
            butIgnorar.Attributes.Add("onClick", "javascript:return confirm('Are you sure you want to ignore?');");
            TableCell tc = new TableCell();
            tc.Controls.Add(butIgnorar);
            e.Row.Cells.Add(tc);
        }
    }

Finally, you call the command from the RowCommand

protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        string currentCommand = e.CommandName;
        string parameter= e.CommandArgument.ToString();

        if (currentCommand.Equals("Ignorar"))
        {
            yourMethodName(parameter);
        }
    }

Hope that this is helpful for somebody!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM