12

how can I add to GridView dynamically some columns based on condition?

  <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>
0

2 Answers 2

18

Try this:

BoundField test = new BoundField();
test.DataField = "New DATAfield Name";
test.Headertext = "New Header";
CustomersGridView.Columns.Add(test);
Sign up to request clarification or add additional context in comments.

2 Comments

@uuser3305953 - To use above code, you should first make autogeneratecolumns="false"
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
7

First set the property of your GridView yourGridView.AutoGenerateColumns = false then add following code to server side:

BoundField newColumn = new BoundField();

newColumn.DataField = "New DATAfield Name";
newColumn.HeaderText = "New Header";

yourGridView.Columns.Add(newColumn);

Note: Here newColumn is your Dynamic Column that you want to add, and yourGridView is your GridView name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.