Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Combobox to DataGridView Headers

Tags:

c#

winforms

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

like image 317
user2576562 Avatar asked Aug 01 '13 08:08

user2576562


1 Answers

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;
like image 88
No Idea For Name Avatar answered Sep 29 '22 08:09

No Idea For Name