ASP.NET动态地将列添加到Gridview

时间:2014-02-13 12:22:34

标签: c# asp.net

如何根据条件动态地向GridView添加一些列?

  <asp:gridview id="CustomersGridView" 
    datasourceid="CustomersSource" 
    autogeneratecolumns="true"
    emptydatatext="No data available." 
    runat="server">

    <columns>
      <asp:boundfield datafield="CustomerID" headertext="Customer ID"/>
      <asp:boundfield datafield="CompanyName" headertext="Company Name"/>
      <asp:boundfield datafield="Address" headertext="Address"/>
      <asp:boundfield datafield="City" headertext="City"/>
      <asp:boundfield datafield="PostalCode" headertext="Postal Code"/>
      <asp:boundfield datafield="Country" headertext="Country"/>
    </columns>
    for(int i; i < length; i++)
      <asp:boundfield datafield="text" headertext="text"/>
  </asp:gridview>

2 个答案:

答案 0 :(得分:12)

试试这个:

BoundField test = new BoundField();
test.DataField = "New DATAfield Name";
test.Headertext = "New Header";
CustomersGridView.Columns.Add(test);

答案 1 :(得分:-2)

Really good article关于C#和VB.Net中的示例。它甚至还展示了如何动态添加 TemplateField