C# GridView中具有动态下拉列表列的动态ItemTemplate

C# GridView中具有动态下拉列表列的动态ItemTemplate,c#,asp.net,gridview,drop-down-menu,C#,Asp.net,Gridview,Drop Down Menu,我正在尝试在asp.net gridview中创建动态列,在这些动态列中,我需要插入一个动态下拉列表。最终结果应该如下所示: public class GridViewTemplate : ITemplate { //A variable to hold the type of ListItemType. readonly ListItemType _templateType; //A variable to hold the colum

我正在尝试在asp.net gridview中创建动态列,在这些动态列中,我需要插入一个动态下拉列表。最终结果应该如下所示:

 public class GridViewTemplate : ITemplate
    {
        //A variable to hold the type of ListItemType.
        readonly ListItemType _templateType;
        //A variable to hold the column name.
        readonly string _columnName;
        //Constructor where we define the template type and column name.

        public GridViewTemplate(ListItemType type, string colname)
        {
            //Stores the template type.
            _templateType = type;

            //Stores the column name.
            _columnName = colname;

        }

        void ITemplate.InstantiateIn(Control container)
        {
            if (_templateType == ListItemType.Item)
            {
                //Creates a new drop down list control.
                DropDownList ddl = new DropDownList {ID = _columnName}; 
                ddl.Attributes.Add("class","chosen-select");
                ddl.Width = 70;
                //get the data to populate ddl
                var tList = Utilities.GetCourseKeys().ToList();
                var selectedValues = (from t in tList select new ListItem( t.KeyValue, t.TrainingPredefinedCourseKeyID.ToString())).ToList();
                //add empty option to items and bind
                selectedValues.Insert(0, new ListItem());
                ddl.DataSource = selectedValues;
                ddl.DataBind();
                // ddl.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
                container.Controls.Add(ddl); //Adds the newly created ddl to the container.
            }
        }
    }

请注意该网格的右上角,其中有HSE1、HSE2等。在上面的示例中,这些列的含义将发生变化。我可能还有一个额外的HSE8、HSE9等。这些列基本上是动态的。为了做到这一点,我做了以下工作,下面是我对gridview的asp.net标记:

 <asp:GridView ID="gvMain" runat="server"
    AutoGenerateColumns="False"
    Width="100%" DataKeyNames="AreaLevelCostCenterFunctionID" OnPreRender="gvMain_PreRender" >
    <Columns>
        <asp:TemplateField HeaderText="JobTitle" >
            <ItemTemplate>
                <asp:HyperLink CssClass="loaderLink" ID="hlAreaLevel" runat="server" NavigateUrl='<%# "/Views/Training/AreaLevel/Details.aspx?AreaLevelID=" + 
                    Eval("AreaLevelCostCenter.AreaLevelID") %>' Text='<%# Eval( "AreaLevelCostCenter.AreaLevel.AreaLevel1" )%>' ToolTip="Area Level">
                </asp:HyperLink>
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Left"></ItemStyle>
            <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
        </asp:TemplateField>

        <!--HERE'S WHERE I ADD MY DYNAMIC COLUMNS -->
    </Columns>
    <PagerSettings Position="TopAndBottom" />
</asp:GridView>
注意我是如何做的
bfield.ItemTemplate=newGridViewTemplate(ListItemType.Item,course.TrainingPredefinedCourse1)我必须创建一个界面来支持此功能。有关更多信息,请参阅此stackoverflow帖子:

基本上,该界面如下所示:

 public class GridViewTemplate : ITemplate
    {
        //A variable to hold the type of ListItemType.
        readonly ListItemType _templateType;
        //A variable to hold the column name.
        readonly string _columnName;
        //Constructor where we define the template type and column name.

        public GridViewTemplate(ListItemType type, string colname)
        {
            //Stores the template type.
            _templateType = type;

            //Stores the column name.
            _columnName = colname;

        }

        void ITemplate.InstantiateIn(Control container)
        {
            if (_templateType == ListItemType.Item)
            {
                //Creates a new drop down list control.
                DropDownList ddl = new DropDownList {ID = _columnName}; 
                ddl.Attributes.Add("class","chosen-select");
                ddl.Width = 70;
                //get the data to populate ddl
                var tList = Utilities.GetCourseKeys().ToList();
                var selectedValues = (from t in tList select new ListItem( t.KeyValue, t.TrainingPredefinedCourseKeyID.ToString())).ToList();
                //add empty option to items and bind
                selectedValues.Insert(0, new ListItem());
                ddl.DataSource = selectedValues;
                ddl.DataBind();
                // ddl.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
                container.Controls.Add(ddl); //Adds the newly created ddl to the container.
            }
        }
    }

当我发回或刷新这些数据时,基本上会遇到两个问题。一个问题是这些列最终会重复它们自己。另一个问题是数据绑定停止工作(即x,y值变为空)。

我认为您应该动态创建整个网格,请参阅下面的代码

                    string tempnum = "txtbox";
                    TemplateField temp1 = new TemplateField();
                    temp1.HeaderStyle.Width = Unit.Pixel(101);
                    temp1.HeaderStyle.CssClass = "headerwidth";
                    temp1.HeaderText = "txt";
                    temp1.ItemTemplate = new CreateTextBox(tempnum);
                    GridView1.Columns.Add(temp1);

在我的示例中,当您在
Page\u Init
中创建动态模板字段并在
Page\u Load
中执行GridView数据绑定时,它就起作用了。我已经测试过了,如果有回发,没有添加额外的列,所有的DropDownLists仍然存在,包含所有数据,如果在回发之前更改了它们,那么它们的selectedvalue将正确显示

protected void Page_Init(object sender, EventArgs e)
{
    //create a loop for the dynamic fields
    for (int i = 1; i < 6; i++)
    {
        //create a new template field
        TemplateField field = new TemplateField();
        field.HeaderText = "HSE " + i;

        //create the new itemtemplate
        field.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "HSE_" + i);

        //add the field to the grid 
        GridView1.Columns.Add(field);
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    //normal use of IsPostBack
    if (!IsPostBack)
    {
        //bind the gridview data
        GridView1.DataSource = LoadFromDataBase();
        GridView1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Text = "PostBack is done!";
}

public class GridViewTemplate : ITemplate
{
    private DataControlRowType templateType;
    private string columnName;

    public GridViewTemplate(DataControlRowType type, string colname)
    {
        templateType = type;
        columnName = colname;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (templateType)
        {
            case DataControlRowType.DataRow:
                DropDownList list = new DropDownList();
                list.DataSource = LoadFromDataBase();
                list.DataTextField = "myText";
                list.DataValueField = "myValue";
                list.DataBind();
                container.Controls.Add(list);
                break;

            default:
                break;
        }

    }
}
受保护的无效页\u Init(对象发送方,事件参数e)
{
//为动态字段创建循环
对于(int i=1;i<6;i++)
{
//创建新模板字段
TemplateField=新建TemplateField();
field.HeaderText=“HSE”+i;
//创建新的itemtemplate
field.ItemTemplate=新的GridViewTemplate(DataControlRowType.DataRow,“HSE_”+i);
//将该字段添加到网格中
GridView1.Columns.Add(字段);
}
}
受保护的无效页面加载(对象发送方、事件参数e)
{
//IsPostBack的正常使用
如果(!IsPostBack)
{
//绑定gridview数据
GridView1.DataSource=LoadFromDataBase();
GridView1.DataBind();
}
}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{
按钮1.Text=“回发完成!”;
}
公共类GridViewTemplate:ITemplate
{
私有DataControlRowType templateType;
私有字符串列名;
公共GridViewTemplate(DataControlRowType类型,字符串colname)
{
模板类型=类型;
columnName=colname;
}
public void实例化EIN(System.Web.UI.Control容器)
{
开关(模板类型)
{
案例DataControlRowType.DataRow:
DropDownList list=新的DropDownList();
list.DataSource=LoadFromDataBase();
list.DataTextField=“myText”;
list.DataValueField=“myValue”;
list.DataBind();
container.Controls.Add(列表);
打破
违约:
打破
}
}
}
使用ASPX完成示例

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"></asp:GridView>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />




BuildGridAdditionalColumns是做什么的?我更新了这篇文章,以便更好地进行澄清。我给了你一个公开的奖励,帮助你获得一些可见性。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"></asp:GridView>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />