将组合框添加到 DataGridView 标头 [英] Adding Combobox to DataGridView Headers
问题描述
当我运行我的代码时,dataGridView TopLeftHeaderCell 也有一个组合框.我该如何改变?
When I run my code, the dataGridView TopLeftHeaderCell has a combobox too. How can I change that ?
这是我的代码:
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;
}
}
谢谢
推荐答案
在你的代码中,
comboBoxHeaderCell.Location = dataGridView.GetCellDisplayRectangle(i, -1, true).Location;
将始终返回 0,0
,因此您将 ComboBox
放在 DataGridView
的位置 0,0
代码>,这就是为什么我们看到这个
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
您可以使用 dataGridView1[i,0].size
来获得所需的大小
you can use dataGridView1[i,0].size
for the size needed
我正在寻找位置
我找不到,但你可以做的是使用 dataGridView1.Width - dataGridView1[1,0].Size.Width
您可以使用宽度,并删除所有标题宽度的大小,然后将它们一一添加.
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;
这篇关于将组合框添加到 DataGridView 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!