如何模板列添加到后面的code一个gridview? [英] How to add TemplateField to a gridview in the code behind?

查看:139
本文介绍了如何模板列添加到后面的code一个gridview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉其中有表的列表列表框。在它存在的GridView。根据从下拉列表框中选择的表,我将动态填充GridView控件。由于表可以有不同的列名,我需要创建模板字段为GridView动态。以下是我的绑定功能。我有两个问题
(1)我不能在包装如果(!的IsPostBack)结合部,因为在GridView是基于下拉列表中选择填充,所以每次我改变选择,列将被复制
(2)我没有任何的数据,我想我需要设置TFIELD(模板列)的ItemTemplate中,但我怎么做呢?

 私人无效BindGridView()
{
DataSet的DS =新的DataSet();尝试
{
DS = ...
如果(ds.Tables.Count大于0)
{的foreach(DataColumn的DC IN ds.Tables [0] .Columns)
{
模板列= TFIELD新的TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(TFIELD);
}
GridView2.DataSource = ds.Tables [0];
GridView2.DataBind();
}
其他
{
...
}
}
赶上(异常前)
{
...}
}


解决方案

有是应该被照顾的各个步骤:

步骤I:
创建一个类继承<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate%28v=vs.110%29.aspx\"><$c$c>ITemplate接口。覆盖功能<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.instantiatein%28v=vs.110%29.aspx\"><$c$c>InstantiateIn()了Itemplate 接口。

第二步:

定义你的类的构造函数带有一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemtype%28v=vs.110%29.aspx\"><$c$c>ListItemType对象作为参数。<​​/ P>

第三步:

如果被添加到容器的控件的控件集合有
绑定到数据源的一些列,然后注册
处理程序 OnDataBinding 事件。当事件发生时,检索
从数据源中的文本,并将其分配给你的控制。例如,被定义为将数据绑定到里面的ItemTemplate 创建你的控件 hyprLnk_DataBinding 事件。

 公共类TemplateGenerator://了Itemplate类继承了Itemplate
    {
        ListItemType类型;
        串COLUMNNAME;
        公共TemplateGenerator(ListItemType T,串CN)
        {
           键入= T;
           COLUMNNAME = CN;
        }
        //覆盖InstantiateIn()方法
        无效ITemplate.InstantiateIn(System.Web.UI.Control容器)
        {
            开关(类型)
            {
                案例ListItemType.Item:
                   超链接hyprLnk =新的超链接();
                   hyprLnk.Target =_blank; //可选的。
                   hyprLnk.DataBinding + =新的EventHandler(hyprLnk_DataBinding);
                   container.Controls.Add(hyprLnk);
                打破;
            }
        }
 //您的控件的DataBinding事​​件
 无效hyprLnk_DataBinding(对象发件人,EventArgs的发送)
      {
        超链接hyprlnk =(超链接)发送;
        GridViewRow容器=(GridViewRow)hyprlnk.NamingContainer;
        反对bindValue =的DataBinder.Eval(的Container.DataItem,COLUMNNAME);
      //如果添加列检查允许空值
        如果(bindValue!= DBNull.Value)
        {
            hyprlnk.Text = bindValue.ToString();
            hyprlnk.NavigateUrl =htt​​p://www.google.com
        }
     }

这就是全部。以上只是创建的ItemTemplate 动态为 GridView控件和控件添加到项模板样本。

现在,下面是将实际执行调用动态创建模板列的功能。需要例如,当你可以调用这个函数从DROPDOWNLIST事件处理程序。

 保护无效GenerateGridViewColumnsDynamically()
        {
            //创建模板列
            模板列的firstName =新的TemplateField();
            firstName.HeaderText =将First_Name;
            firstName.ItemTemplate =新TemplateGenerator(ListItemType.Item,
                                                          名字);
            //显示绑定列的例子只是为了更多的上下文
            绑定列的lastName =新的BoundField();
            lastName.DataField =姓氏;
            lastName.HeaderText =姓氏;
           //现在添加列
            MyGridView.Columns.Add(名字);
            MyGridView.Columns.Add(lastName的);
        }

注意:名字和姓氏的是他们的名字被传递到您的自定义类的构造函数列:TemplateGenerator

I have a drop down list box which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically. Following is my bind function. I have two problems (1) I couldn’t wrap the binding part in If (!IsPostBack) since the GridView is populated based on the selection of the drop down list, so everytime I change the selection, the columns will be duplicated (2) And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?

private void BindGridView()
{
DataSet ds = new DataSet();

try
{
ds = …
if (ds.Tables.Count > 0)
{

foreach (DataColumn dc in ds.Tables[0].Columns)
{
TemplateField tField = new TemplateField();
tField.HeaderText = dc.ColumnName;
GridView2.Columns.Add(tField);
}


GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
}
else
{
…
}
}
catch (Exception ex)
{
…

}
}

解决方案

There are various steps that should be taken care of:

STEP I:: Create a Class inheriting the ITemplate interface. Overwrite the function InstantiateIn() of the ITemplate interface.

STEP II:

Define a constructor for your Class that takes a ListItemType object as its parameter.

STEP III::

If the control being added to the container's Controls collection has to be bound to some datasource Column, then register the handler for the OnDataBinding event. When the event occurs, retrieve the text from the data source and assign it to your control. For Example, hyprLnk_DataBinding event is defined for Binding Data to your controls created inside ItemTemplate.

public class TemplateGenerator : ITemplate // Class inheriting ITemplate
    {
        ListItemType type;
        string columnName;    
        public TemplateGenerator(ListItemType t, string cN)
        {           
           type = t;    
           columnName= cN;    
        }
        // Override InstantiateIn() method
        void ITemplate.InstantiateIn(System.Web.UI.Control container)
        {    
            switch (type)
            {
                case ListItemType.Item:    
                   HyperLink hyprLnk = new HyperLink();
                   hyprLnk.Target = "_blank"; //Optional.
                   hyprLnk.DataBinding+=new EventHandler(hyprLnk_DataBinding);
                   container.Controls.Add(hyprLnk);
                break;      
            }
        }    
 // The DataBinding event of your controls
 void hyprLnk_DataBinding(object sender, EventArgs e)
      {    
        HyperLink hyprlnk = (HyperLink)sender;
        GridViewRow container = (GridViewRow)hyprlnk.NamingContainer;
        object bindValue = DataBinder.Eval(container.DataItem,columnName);
      // Adding check in case Column allows null values
        if (bindValue != DBNull.Value) 
        {
            hyprlnk.Text = bindValue.ToString();
            hyprlnk.NavigateUrl = "http://www.google.com";
        }
     }

That's all. Above was just a sample to create ItemTemplate dynamically for GridView and add controls to the Item Template.

Now, Below is the function that will actually carry out the calls to create Template Columns dynamically. You can call this function when required for e.g. from your DropDownlist event Handler.

protected void GenerateGridViewColumnsDynamically()
        {
            // Create the TemplateField 
            TemplateField firstName = new TemplateField();
            firstName.HeaderText = "First_Name"; 
            firstName.ItemTemplate = new TemplateGenerator(ListItemType.Item,
                                                          "FirstName");
            // Showing boundField example just for more context
            BoundField lastName = new BoundField();
            lastName.DataField = "LastName";
            lastName.HeaderText = "Last_Name";
           // Add the Columns now
            MyGridView.Columns.Add(firstName);
            MyGridView.Columns.Add(lastName);
        }

NOTE:: FirstName and LastName are the Columns whose Names are passed to the Constructor of your custom Class: TemplateGenerator

这篇关于如何模板列添加到后面的code一个gridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆