Frage

I have added a bunch of columns to a DataGridView like this through code.

dgvDocDisplay.ColumnCount = 22;
dgvDocDisplay.Columns[0].Name = "Tag";
dgvDocDisplay.Columns[1].Name = "[ ]";
dgvDocDisplay.Columns[2].Name = "#";
dgvDocDisplay.Columns[3].Name = "Type";
dgvDocDisplay.Columns[4].Name = "Reference";

Now I want to make the 3rd column display checkboxes (the rows of that column, not the header). I did quite a bi of search and came across articles like this one but the method shown there would only insert a new column with checkboxes.

DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
dgvDocDisplay.Columns.Add(col);

What I need is to add a checkbox column to an already existing column. Unfortunately I couldn't find anything regarding that.

How can I add checkboxes to an existing column?

War es hilfreich?

Lösung

If you're adding the columns yourself, why not add the type of column you need when you do that? Like this:

dgvDocDisplay.Columns.AddRange(
    new DataGridViewColumn[]
    {
        new DataGridViewTextBoxColumn { Name = "Tag" },
        new DataGridViewTextBoxColumn { Name = "[ ]" },
        new DataGridViewCheckBoxColumn { Name = "#" },
        new DataGridViewTextBoxColumn { Name = "Type" }
        // etc
    });

Andere Tipps

You will have to remove the current column from your collection and push in a new column of the desired type in that position.

you can use grid.RemoveAt(yourindex); to remove

then you can insert the desired one like

grid.Columns.Insert(yourindex, new DataGridViewCheckBoxColumn())

Or you may just use grid.Columns.Add(new DataGridViewCheckBoxColumn()) and then set the DisplayIndex property of this column to your required index.

have you tried:

dgvDocDisplay.Columns[2] = new DataGridViewCheckBoxColumn();

?

this

DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
dgvDocDisplay.Columns.Add(col);

indeed adds a new column thus the Columns.Add()

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top