1

I am using a DataGridView that depending on button click has different columns. This is working but it requires a lot of lines of code and I was wondering if this could be done more efficiently.

One of the options for example has 20 columns requiring the following code to be added 20 times each time with a different name:

DataGridViewColumn Column1 = new DataGridViewTextBoxColumn
{
    DataPropertyName = "User",
    Name = "User",
    HeaderText = "User"
};
DataGridView1.Columns.Add(Column1);

This code is repeated 20 times with only "user" being swapped out by a other word and Column1 having it's number increased. Can this be done in something like a loop using a string array containing the names?

ASh
  • 34,632
  • 9
  • 60
  • 82
A.bakker
  • 221
  • 1
  • 9

2 Answers2

3

just add a loop:

var names = new string[] { "User", "something" };

foreach(var name in names)
{

    var column = new DataGridViewTextBoxColumn
    {
        DataPropertyName = name,
        Name = name,
        HeaderText = name 
    };
    DataGridView1.Columns.Add(column);
}
ASh
  • 34,632
  • 9
  • 60
  • 82
0
 private void CreateCol(string Col_Name)
    {
       if (DataGridView1.Columns.Contains (Col_Name)) return ;
        DataGridViewColumn Column1 = new DataGridViewTextBoxColumn
        {
            DataPropertyName = Col_Name,
            Name = Col_Name,
            HeaderText = Col_Name
        };
        DataGridView1.Columns.Add(Column1);

    }
nanda9894
  • 61
  • 5