简体   繁体   English

如何在asp.net gridview行的底部动态添加按钮

[英]How to add buttons dynamically at the bottom of an asp.net gridview row

I am working on an asp.net webforms C# gridview. 我正在使用asp.net Webforms C#gridview。 It is a nested gridview. 它是一个嵌套的gridview。 Each child grid will have only two rows. 每个子网格只有两行。 The second row of the each child grid will have an action button at the last column. 每个子网格的第二行在最后一列将具有一个操作按钮。 Up to this point I have completed and everything is working fine. 至此,我已经完成,一切正常。 Depending upon the data type, I have to add four buttons to some of the child rows at the bottom. 根据数据类型,我必须在底部的某些子行中添加四个按钮。 My entire child grid is created dynamically and added to the parent grid. 我的整个子网格都是动态创建的,并已添加到父网格。 The child grid has six columns, which I create as a boundfield and either set the text to a value or add a button to the sixth column. 子网格有六列,我将它们创建为边界域,然后将文本设置为值或将按钮添加到第六列。 If needed I could change them into template fields. 如果需要,我可以将它们更改为模板字段。 I am not sure whether a footer of a template field can be used to add the four buttons. 我不确定模板字段的页脚是否可用于添加四个按钮。

Thanks 谢谢

There is little info to go on, but since you state that you create the Nested Grid dynamically i think you are familiar with the RowDataBound event. 几乎没有任何信息可做,但是由于您声明要动态创建嵌套网格,因此我认为您对RowDataBound事件很熟悉。 You can use that to add Buttons as well. 您也可以使用它来添加按钮。 In this snippet I add the buttons to the footer row, so you have to enable that row in the nested grid: ShowFooter="true" 在此代码段中,我将按钮添加到页脚行中,因此您必须在嵌套网格中启用该行: ShowFooter="true"

bool primary = false;

protected void NestedGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the current row is a datarow or a footer row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (column == value)
        {
            primary = true;
        }
    }
    else if (e.Row.RowType == DataControlRowType.Footer && primary == true)
    {
        //create 4 buttons in a loop
        for (int i = 0; i < 4; i++)
        {
            //create a new button
            Button button = new Button();
            button.Text = "Button " + (i + 1);

            //add a click handler to the button
            button.Click += Button1_Click;

            //add the button to the footer row
            e.Row.Cells[i].Controls.Add(button);
        }
    }
}

Because you are adding controls dynamically to the GridView, databinding has to occur on every page load, so move the databinding outside the if (!Page.IsPostBack) { } check. 因为要向GridView动态添加控件,所以每次页面加载时都必须进行数据绑定,因此请将数据绑定移到if (!Page.IsPostBack) { }检查之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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