数据绑定后,GridView Column.Count始终为0 [英] GridView Column.Count is always 0 after databind with a datatable

查看:230
本文介绍了数据绑定后,GridView Column.Count始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在创建一个动态的DataTable,然后将其绑定到GridView



后来,在回帖后,我正在检查条件,并希望显示/隐藏GridView的几列,但Column.Count也是0!



我的代码如下 -
ASPX页面

 < asp:GridView ID = GridView1runat =server> 
< / asp:GridView>

.CS页面

  protected void Button1_Click(object sender,EventArgs e)
{
DataTable aDT = new DataTable()
aDT = createDataTable(); // datatable有21列

GridView1.DataSource = aDT;
GridView1.DataBind();

int temp = GridView1.Columns.Count; //总是0
}

不知道代码有什么问题

解决方案

如果将 autogeneratedcolumns 属性设置为 true 然后计数将始终显示0。



MSDN


列属性(collection)用于存储在GridView控件中呈现的所有明确的
声明的列字段。您
也可以使用Columns集合以编程方式管理
列字段集合。


在您的情况下,您没有明确声明您的列。因此,如果GridView包含至少一行,则可以在Click方法的内部和外部获取列数:


单元格连续计数=列计数。




  if(GridView1.Rows.Count> 0)
int temp = GridView1.Rows [0] .Cells.Count;

或者你可以从DataTable里获取点数像@ TimSchmelter 发表评论:

  int temp = aDT .Columns.Count 


I am trying to show/hide GridView columns conditionally.

I am creating a dynamic DataTable and then Binding it to the GridView

Later, on a post back, I am checking condition and want to show/hide a few columns of the GridView, but Column.Count is alway 0!

The code I have is as below - ASPX page

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

.CS Page

 protected void Button1_Click(object sender, EventArgs e)
{
   DataTable aDT = new DataTable()
   aDT = createDataTable();   //datatable has 21 columns

   GridView1.DataSource = aDT;
   GridView1.DataBind();

   int temp = GridView1.Columns.Count;   //always 0
}

Not sure what is wrong with the code

解决方案

If you set the autogeneratedcolumns property to true then the count will always show 0.

From MSDN

The Columns property (collection) is used to store all the explicitly declared column fields that get rendered in the GridView control. You can also use the Columns collection to programmatically manage the collection of column fields.

In your case, you didn't declared your columns explicitly. So you can get columns count like this inside and outside of the Click method if GridView contains at least one row:

Cells Count in a Row = Columns Count.

if(GridView1.Rows.Count>0)
    int temp = GridView1.Rows[0].Cells.Count;

Or you can get counts from DataTable inside Click method like that as @TimSchmelter commented:

int temp = aDT.Columns.Count

这篇关于数据绑定后,GridView Column.Count始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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