Ren
Ren

Reputation: 775

Add new column at specified position programmatically in C# Datagridview

I have a datagridview with 5(0-5) columns. All the rows value I retrieve from the hashtable created. Now I've set a condition that state if column 4 contain empty value from hashtable then add new column next to column 4 which makes the new added column index at position 5 and the value of hashtable previously for column 5 change to column 7.

I do the code like this:

    int number = dataGridView1.Rows.Add();
    dataGridView1.Rows[number].Cells[0].Value = result;                                 //id       
    dataGridView1.Rows[number].Cells[1].Value = newAddress;                             //ip    
    dataGridView1.Rows[number].Cells[2].Value = (string)((Hashtable)ht[1])["value"];    //name
    dataGridView1.Rows[number].Cells[3].Value = (string)((Hashtable)ht[2])["value"];    //description
    if (!ht.ContainsValue(3))
        {
          // Create a Save button column
          DataGridViewImageButtonSaveColumn columnSave = new DataGridViewImageButtonSaveColumn();

          // Set column values
          columnSave.Name = "SaveButton";
          columnSave.HeaderText = "";

          //Add the columns to the grid
          dataGridView1.Rows[number].Cells[4].ReadOnly = false;
          dataGridView1.Columns[5].Add(columnSave);    //im not sure about this codes
          dataGridView1.Rows[number].Cells[6].Value = (string)((Hashtable)ht[4])["value"];    //count

        } 
        else
        {
          dataGridView1.Rows[number].Cells[4].Value = (string)((Hashtable)ht[3])["value"];    //location
          dataGridView1.Rows[number].Cells[5].Value = (string)((Hashtable)ht[4])["value"];    //count
        }

However, i'm not sure if I do this right because I receive error at the line commented

        dataGridView1.Columns[5].Add(columnSave);    //im not sure about this codes

Seems like this code is wrong. Can anyone please advise?

Upvotes: 6

Views: 27296

Answers (2)

Ahmad
Ahmad

Reputation: 11

A simple way to insert a checkbox to certain column of Data grid:

DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();

dataGridView1.Columns.Insert(**certain column number**, chk);

for example if you want to add checkbox to column 1 you mus type

dataGridView1.Columns.Insert(0, chk); 

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103467

Try dataGridView1.Columns.Insert(5, columnSave); instead.

MSDN reference: DataGridViewColumnCollection.Insert Method

Upvotes: 17

Related Questions