11

When I run my code, the dataGridView TopLeftHeaderCell has a combobox too. How can I change that ?

Here's my code :

public void AddHeaders(DataGridView dataGridView)
{

        for (int i = 0; i < 4; i++)
        {
            // Create a ComboBox which will be host a column's cell
            ComboBox comboBoxHeaderCell = new ComboBox();
            comboBoxHeaderCell.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBoxHeaderCell.Visible = true;

            foreach (KeyValuePair<string, string> label in _labels)
            {
                comboBoxHeaderCell.Items.Add(label.Key);
            }

            // Add the ComboBox to the header cell of the column
            dataGridView.Controls.Add(comboBoxHeaderCell);
            comboBoxHeaderCell.Location = dataGridView.GetCellDisplayRectangle(i, -1, true).Location;
            comboBoxHeaderCell.Size = dataGridView.Columns[0].HeaderCell.Size;
            comboBoxHeaderCell.Text = _labels[i].Key;

        }
}

Thank you

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user2576562
  • 233
  • 1
  • 4
  • 7

2 Answers2

1

at your code,

comboBoxHeaderCell.Location = dataGridView.GetCellDisplayRectangle(i, -1, true).Location;

will always return 0,0, and therefor you put your ComboBox at location 0,0 in the DataGridView, and that's why we see this

enter image description here

you can use dataGridView1[i,0].size for the size needed

i'm looking for location

i couldn't find that, but what you can do is using the dataGridView1.Width - dataGridView1[1,0].Size.Width you can use the width, and remove the size of all the headers width, and then add them one by one.

int xPos = dataGridView1.Width;

for (int i = 0; i < 4; i++)
{
   xPos -= dataGridView1[i, 0].Size.Width;
}
 ...
comboBoxHeaderCell.Size = dataGridView.Columns[0].HeaderCell.Size;
comboBoxHeaderCell.Location = new Point(xPos, 0);
xPos += comboBoxHeaderCell.Size.Width;
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
1
    public void AddHeaders(DataGridView dataGridView)
 {

    for (int i = 0; i < 4; i++)
    {
        // Create a ComboBox which will be host a column's cell
        DataGridViewComboBoxCell comboBoxHeaderCell = new DataGridViewComboBoxCell();           


        foreach (KeyValuePair<string, string> label in _labels)
        {
            comboBoxHeaderCell.Items.Add(label.Key);
        }

        // Add the ComboBox to the header cell of the column
        dataGridView[i, 0] = comboBoxHeaderCell;
        comboBoxHeaderCell.Value =_labels[i].Key;


    }
}

try this it will solve your problem, i removed those lines they are not mandatory to keep as by default it will be visible... and by default it will take cell size...

Deadlock
  • 330
  • 1
  • 3
  • 21
  • I have an error saying that the index DataGridViewCell.Visible, DataGridViewCell.Size, DataGridViewCell.Test, is not assigned, it's on read only – user2576562 Aug 01 '13 at 13:16