如何在代码后端添加GridView列?

11

我正在尝试在ASP.NET 2.0中为GridView添加一列。

gridViewPoco.Columns.Add(...)

然而,我找不到合适的选项。我想要以下选项的等价物:

<asp:BoundField>
<asp:TemplateField>
2个回答

16

例如:

protected void Btn_AddCol_Click(object sender, EventArgs e)
{
    TemplateField tf = new TemplateField();
    tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
    tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
    MyGridView.Columns.Add(tf);
}
  • 定义新的TemplateField
  • 设置列标题名称(Col1)和类型(Int32
  • 设置列值类型(Int32
  • 将此字段添加到您的Gridview

谢谢你,我之前在一个程序中也遇到了同样的问题。嘿,你能帮忙解决这个问题吗?http://stackoverflow.com/questions/20708957/c-sharp-metro-xaml-designing-the-page-for-any-of-the-screen - TheQuestioner
@Downvoter,您能否至少评论一下,这样我就可以看到我可能错在哪里了? - Soner Gönül
当我尝试运行你的代码时,为什么会出现“找不到类型或命名空间GridViewLabelTemplate(您是否缺少使用指令或程序集引用?)”这样的错误? - Koray Durudogan
@KorayDurudogan 请查看:http://www.developer.com/net/asp/article.php/3609991/在ASPNET 20 GridView控件中使用动态模板列.htm - Soner Gönül

5

Soner的答案非常适用于向GridView添加列。但是,如果您发现自己需要在GridView中间添加列,则需要采用稍微不同的方法(使用MyGridView.Columns.Insert()函数):

  protected void Btn_AddCol_Click(object sender, EventArgs e)
    {
    TemplateField tf = new TemplateField();
    tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
    tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
    MyGridView.Columns.Insert(2, tf); //the 2 makes it go into the third column -- zero-based indexing ftw
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接