8

how to add column dynamically in datagridview using c#

4 Answers 4

12

For example:

        DataGridViewColumn col = new DataGridViewTextBoxColumn();
        col.HeaderText = "Hi there";
        int colIndex = grid.Columns.Add(col);
Sign up to request clarification or add additional context in comments.

1 Comment

I get 'DataGridViewColumn' is a type and cannot be used as an expression.
2

If it's like any of the other .Net grid controls:

YourDataGridView.Columns.Add(New DataGridViewColumn());

2 Comments

Columns.Add can throw an exception if the CellType property of your DataGridViewColumn is null. I believe it's better to set the DataGridViewColumn's CellTemplate before adding it (CellType is the runtime type of CellTemplate), or to use a class that inherits from DataGridViewColumn for which CellTemplate is already set appropriately.
@Tim Goodman - I'd agree, my example is just to show basically how it can be done. An actual implementation would be a bit more involved.
1

I you mean to add all value on particular column then maybe it could help you.

Try this tips:

for (int i=0; i< datagriview1.coulums.count -1; i++)
{
  int total + = total + datagridview1.columns[i]
    .cell[index for columns you want to add].formatedvalue.toString();  

}

textbox1.text=total;

Try that code. it can help you.

Thanks, Nico

Comments

0

I am also tested this code you mean to add all value on particular column then maybe it could help you. Try this tips:

gridView1.Columns.Clear();
gridView1.Columns.Add(new GridColumn() {Caption = @"Caption", FieldName = "FieldName", Name = "FieldName", Visible = true});

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.