【问题标题】:How to add a GridView Column on code-behind?如何在代码隐藏中添加 GridView 列?
【发布时间】:2011-08-26 10:28:45
【问题描述】:

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

gridViewPoco.Columns.Add(...)

但是,我找不到正确的选项。我想要以下等价物:

<asp:BoundField>
<asp:TemplateField>

【问题讨论】:

    标签: c# asp.net gridview code-behind


    【解决方案1】:

    例如;

    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

    【讨论】:

    • 谢谢你,前段时间我在一个程序中遇到了同样的问题。嘿,你能解决这个问题吗? stackoverflow.com/questions/20708957/…
    • @Downvoter 至少愿意发表评论,这样我才能看到我可能哪里出错了?
    • 当我尝试您的代码时,为什么会出现“找不到类型或命名空间 GridViewLabelTemplate”之类的错误(您是否缺少 using 指令或程序集引用?)?
    【解决方案2】:

    Soner's Answer 非常适合将列添加到 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
        }
    

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多