2011-02-25 73 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文章的細節。