动态创建GridView的列(2)


    ·使用LoadTemplate()方法
    ·创建自定义模板列


使用LoadTemplate()方法增加TemplateField
为了本例的实现,你需要在Visutal Studio新建一个websit。拖拽一个GridView和SqlDataSource到默认页。我们将通过编码设置这些控件的一些列属性。首先,我们将使用LoadTemplate()方法来增加一个TemplateField。LoadTemplate()方法对于页面上所有的模板控件来说都是可用的。它通过虚拟路径加载模板。LoadTemplate()的返回值是一个实现了ITemplate接口的对象。

在我们的例子里我们将在用户控件里创建一个模板。在website里新建一个名为ItemTemplate.ascx的用户控件。其关键代码如下。

ExpandedBlockStart.gif ContractedBlock.gif <% dot.gif @ Control Language="C#" AutoEventWireup="true" CodeFile="ItemTemplate.ascx.cs" Inherits="ItemTemplate"  %>
None.gif
< asp:Label  ID ="Label1"  runat ="server"  Text ='<%#  Eval("EmployeeID") % > '> </ asp:Label >
None.gif
< asp:Label  ID ="Label2"  runat ="server"  Text ='<%#  Eval("FirstName") % > '> </ asp:Label >
None.gif
< asp:Label  ID ="Label3"  runat ="server"  Text ='<%#  Eval("LastName") % > '> </ asp:Label >


仔细看一下上面的标记。它包含了3个Label控件。每个Label控件的Text属性分别绑定了Employees表的EmployeeID,FirstName和LastName列。Eval()表达式是asp.net中的一种数据绑定方法,它使用列的名字去绑定。这个用户控件稍后将在我们的ItemTemplate中使用。

现在打开默认webform的代码编辑窗口,其Page_Load事件中的关键代码如下。

None.gif protected   void  Page_Load( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    SqlDataSource1.ConnectionString 
= @"data source=.;initial catalog=northwind;integrated security=true";
InBlock.gif    SqlDataSource1.SelectCommand 
= "select employeeID,FirstName,LastName from employees";
InBlock.gif
InBlock.gif    
if (!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        GridView1.DataSourceID 
= "SqlDataSource1";
InBlock.gif        GridView1.AutoGenerateColumns 
= false;
InBlock.gif
InBlock.gif        TemplateField tf1 
= new TemplateField();
InBlock.gif        tf1.ItemTemplate
=LoadTemplate("ItemTemplate.ascx");
InBlock.gif        GridView1.Columns.Add(tf1);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


这段代码指出了SQL数据源控件的ConnectionString属性是连到Northwind数据库的。其SelectCommand属性指定为一段select查询语句,它从Employees表中检索出EmployeeID,FirstName和LastName列。然后设置了GridView的DataSourceID属性为该数据源控件的ID。同时AutoGenerateColumns属性设置成false以便动态的增加列。再接下来的那几行代码是非常重要的。首先实例化一个TemplateField类,该类是可以呈现为一个GridView的TemplateColumn。TemplateField类的ItemTemplate属性设置为LoadTemplate()方法的返回值。LoadTemplate()方法使用虚拟路径来加载模板(在我们的例子里模板文件为ItemTemplate.ascx)。然后把这个TemplateField增加到GridView控件的列集合中。

在你的浏览器中运行这个webform将会如下显示。
gridviewdyncol21.jpg

注意如何应用用户控件中指定的模板。同时我们看到标题是空的,因为没有指定HeaderTemplate。你可以指定它或者关闭它。


使用自定义模板类增加TemplateField
现在你已经知道了如何使用LoadTemplate()方法,接下来让我们来看看如何使用另一种方法。在最后的例子中你学到了用LoadTemplate()方法返回一个实现了Itemplate接口的对象。你自己也可以创建这样一个实现了Itemplate接口的类并直接使用它,从而代替LoadTemplate()方法。

我们在App_Code文件夹内新建一个名为MyTemplate的类。其关键代码如下。

None.gif public   class  MyTemplate:ITemplate
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
private string colname; 
InBlock.gif
InBlock.gif    
public MyTemplate(string colname)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.colname = colname; 
ExpandedSubBlockEnd.gif    }
    
InBlock.gif
InBlock.gif    
public void InstantiateIn(Control container)    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{        
InBlock.gif        LiteralControl l 
= new LiteralControl();        
InBlock.gif        l.DataBinding 
+= new EventHandler(this.OnDataBinding);        
InBlock.gif        container.Controls.Add(l);    
ExpandedSubBlockEnd.gif    }
 
InBlock.gif   
InBlock.gif    
public void OnDataBinding(object sender, EventArgs e)    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{        
InBlock.gif        LiteralControl l 
= (LiteralControl)sender;        
InBlock.gif        GridViewRow container 
= (GridViewRow)l.NamingContainer;        
InBlock.gif        l.Text 
= ((DataRowView)container.DataItem)[colname].ToString();    
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


这段代码创建了一个实现了Itemplate接口的名为MyTemplate的类。这个接口只包含一个你必须实现的方法 - InstantiateIn()。这段代码声明了一个变量用来保存被显示的列的名称,该名称在类的构造函数中设置,然后实现InstantiateIn()方法。该方法的参数为一个容器类型或父控件类型的控件的对象。在这里,我们创建了一个LiteralControl和一个DataBinding事件(OnDataBinding)。这个事件在容器控件调用DataBind()方法时发生。然后把这个LiteralControl加到容器控件的控件集合中。

OnDataBinding()事件所作的工作就是把所需的数据绑定到LiteralControl。给容器控件加上NamingContainer属性,然后提取出一个Row。最后,LiteralControl的Text属性被设置为构造函数所指出的列的在数据库中所存储的值。这样,我们的自定义模板类就完成了。

在website里新建一个webform。像以前一样拖拽一个GridView和SqlDataSouce到页上。其Page_Load事件中的代码如下。

None.gif protected   void  Page_Load( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    SqlDataSource1.ConnectionString 
= @"data source=.;initial catalog= northwind;integratedsecurity=true";
InBlock.gif    SqlDataSource1.SelectCommand 
= "select employeeID,FirstName,LastName from employees";
InBlock.gif
InBlock.gif    
if (!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        GridView1.DataSourceID 
= "SqlDataSource1";
InBlock.gif        GridView1.AutoGenerateColumns 
= false;
InBlock.gif
InBlock.gif        TemplateField tf1 
= new TemplateField();
InBlock.gif        MyTemplate t1 
= new MyTemplate("FirstName");
InBlock.gif        tf1.HeaderText 
= "First Name";
InBlock.gif        tf1.ItemTemplate 
= t1;
InBlock.gif
InBlock.gif        TemplateField tf2 
= new TemplateField();
InBlock.gif        MyTemplate t2 
= new MyTemplate("LastName");
InBlock.gif        tf2.HeaderText 
= "Last Name";
InBlock.gif        tf2.ItemTemplate 
= t2;
InBlock.gif
InBlock.gif        GridView1.Columns.Add(tf1);
InBlock.gif        GridView1.Columns.Add(tf2);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


这段代码如从前一样设置了GridView和SqlDataSource的属性。注意代码中加粗的部分(译者注:就是代码的中下部份),它是用来创建TemplateField类的实体的。这次TemplateField的ItemTemplate属性被设置成了实例化的MyTemplate类。列的名称 - FirstName和LastName被传到了构造函数中。TemplateField被增加到了GridView的列集合中。

运行上面的webform将如下显示。
gridviewdyncol22.jpg

转载于:https://www.cnblogs.com/spark_wu/archive/2009/04/13/1434881.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android GridView中动态添加,可以遵循以下步骤: 1. 定义一个基本的GridView布局文件,包含GridView控件和适配器。 2. 创建一个数据源表,用于存储GridView中要显示的数据。 3. 创建一个自定义适配器,该适配器用于将数据源表中的数据绑定到GridView中的单元格中。 4. 在Activity或Fragment中,实例化GridView控件,并将自定义适配器设置为GridView的适配器。 5. 在需要动态添加的时候,更新数据源表,并调用适配器的notifyDataSetChanged()方法,以便GridView可以重新绘制。 6. 在适配器中,根据数据源表的大小来确定GridView中应该显示的数。可以使用GridView的setNumColumns()方法来设置数。 以下是一个简单的示例代码,演示如何动态添加GridView中: ```java public class MainActivity extends AppCompatActivity { private GridView gridView; private CustomAdapter customAdapter; private List<String> dataList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = findViewById(R.id.gridview); dataList = new ArrayList<>(); customAdapter = new CustomAdapter(dataList); gridView.setAdapter(customAdapter); // 动态添加一 addColumn(); } private void addColumn() { // 更新数据源表 dataList.add("New Column"); // 计算数 int numColumns = (dataList.size() % 3 == 0) ? dataList.size() / 3 : (dataList.size() / 3) + 1; // 设置gridView.setNumColumns(numColumns); // 刷新适配器 customAdapter.notifyDataSetChanged(); } class CustomAdapter extends BaseAdapter { private List<String> dataList; public CustomAdapter(List<String> dataList) { this.dataList = dataList; } @Override public int getCount() { return dataList.size(); } @Override public Object getItem(int position) { return dataList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false); } TextView textView = convertView.findViewById(R.id.textview); textView.setText(dataList.get(position)); return convertView; } } } ``` 在上面的示例中,我们在Activity的onCreate()方法中,实例化了一个GridView控件和一个自定义适配器。然后,我们调用了addColumn()方法,该方法会更新数据源表,计算出应该显示的数,并设置到GridView中。最后,我们调用了适配器的notifyDataSetChanged()方法,以便GridView可以重新绘制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值