10

当我运行我的代码时,dataGridView TopLeftHeaderCell 也有一个组合框。我该如何改变呢?

这是我的代码:

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;

        }
}

谢谢

4

2 回答 2

1

在您的代码中,

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

将永远返回0,0,因此您将ComboBoxat 位置0,0放在 中DataGridView,这就是我们看到这个的原因

在此处输入图像描述

您可以使用dataGridView1[i,0].size所需的尺寸

我在找位置

我找不到,但是您可以做的是使用dataGridView1.Width - dataGridView1[1,0].Size.Width 您可以使用的宽度,并删除所有标题宽度的大小,然后将它们一一添加。

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;
于 2013-08-01T08:58:57.300 回答
0
    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;


    }
}

试试这个它会解决你的问题,我删除了那些他们不是必须保留的行,因为默认情况下它是可见的......默认情况下它会占用单元格大小......

于 2013-08-01T09:13:33.590 回答