简体   繁体   English

如何以编程方式向现有 gridview 添加其他列?

[英]How to add additional columns to existing gridview programmatically?

I have a gridview in a user control.我在用户控件中有一个 gridview。 I am using BoundField for displaying columns in gridview in aspx page.我正在使用BoundField在 aspx 页面中显示 gridview 中的列。 Can I add additional columns from code behind file (.cs)?我可以从文件 (.cs) 后面的代码中添加其他列吗? I need to add few additional columns in the user control is used in different page.我需要在不同页面中使用的用户控件中添加一些额外的列。

You can add a new cell in RowDataBound event of the gridview, like below.您可以在 gridview cell in RowDataBound ,如下所示。 (I have added the comments where needed) (我在需要的地方添加了评论)

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
   {
     TableHeaderCell NewCell = new TableHeaderCell();
     NewCell.Text = "Header Text";
     e.Row.Cells.AddAt(4(Index of Cell where you want to add cell), NewCell);
   }


if (e.Row.RowType == DataControlRowType.DataRow)
     {
       TableCell NewCell= new TableCell(); 
       NewCell.ID = "NewCell";
       NewCell.Text = "Text value of cell which you want to display";
       e.Row.Cells.AddAt(4, NewCell);
     }
 }

create a method to add columns in user control, and keep it accessor public.创建一个在用户控件中添加列的方法,并使其访问器公开。 Now call that function from the aspx page where you have you that control object.现在从控制 object 的 aspx 页面调用 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM