2011-02-25 66 views
1

我想动态地添加gridview所有格式和模板字段..动态GridView的所有格式和模板字段

我试着通过下面的方式。

public StringBuilder getTextForGridView() 
{ 
StringBuilder sb = new StringBuilder(); 
sb.AppendLine(" <asp:GridView ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"False\" "); 
sb.AppendLine(" CellPadding=\"4\" ForeColor=\"#333333\" GridLines=\"None\" ShowHeader=\"true\">"); 

sb.AppendLine(" <Columns>"); 

sb.AppendLine(" <asp:TemplateField>"); 
sb.AppendLine(" <HeaderTemplate>"); 

sb.AppendLine(" <asp:Label ID=\"lbl1\" runat=\"server\" Text='<%#Eval(\"Id\")%>'></asp:Label>"); 
sb.AppendLine(" </HeaderTemplate>"); 
sb.AppendLine(" <ItemTemplate>"); 
sb.AppendLine(" <asp:Label ID=\"lbl1\" runat=\"server\" Text='<%#Eval(\"Id\")%>'></asp:Label>"); 

sb.AppendLine(" </ItemTemplate>"); 

sb.AppendLine(" </asp:TemplateField>"); 

sb.AppendLine(" <asp:TemplateField>"); 
sb.AppendLine(" <HeaderTemplate>"); 

sb.AppendLine(" <asp:Label ID=\"lbl1\" runat=\"server\" Text='<%#Eval(\"Name\")%>'></asp:Label>"); 
sb.AppendLine(" </HeaderTemplate>"); 
sb.AppendLine(" <ItemTemplate>"); 
sb.AppendLine(" <asp:Label ID=\"lbl1\" runat=\"server\" Text='<%#Eval(\"Name\")%>'></asp:Label>"); 

sb.AppendLine(" </ItemTemplate>"); 

sb.AppendLine(" </asp:TemplateField>"); 
sb.AppendLine(" </Columns>"); 

sb.AppendLine(" </asp:GridView>"); 

return sb; 
} 

下面的文本文字作为,加入它,然后即时分配给占位

Literal li = new Literal(); 
li.ID = "lit"; 
li.Text = getTextForGridView().ToString(); 

PlaceHolder1.Controls.Add(li); 

,但问题是我不是能够分配的数据源的GridView作为即时通讯没有能够得到GridView控件的对象.. 请让我离开这里。 谢谢。

回答

1

您正在向页面添加一个字符串,您必须向ControlTree添加一个GridView实例,以便ASP.NET知道它。看看这篇文章,以获得更好的理解。

Dynamic Controls in ASP.NET

+0

感谢您的链接... – Nitin 2011-02-25 15:03:28

0

瑞克说,你可以添加一个新的GridView到ControlTree编程:

GridView myGV = New GridView(); 
myGV.ID = "GridView1"; 
myGV.DataSourceID = "SqlDataSource1"; 
... 

你可以让你自动生成的列(与GridView.AutoGenerateColumns属性)或手动添加DataControlFields到列集合:

BoundField col1 = New BoundField(); 
col1.HeaderText = "Column Header Text"; 
col1.DataField = "DataSourceColumn"; 
myGV.Columns.Add(bField); 

GridviewDataControlField MSDN文章的细节。