【问题标题】:Adding Combobox to DataGridView Headers将组合框添加到 DataGridView 标题
【发布时间】:2013-08-01 08:40:04
【问题描述】:

当我运行我的代码时,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;

        }
}

谢谢

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    在您的代码中,

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

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

    您可以使用dataGridView1[i,0].size 来获取所需的大小

    我正在寻找位置

    我找不到,但您可以使用 dataGridView1.Width - dataGridView1[1,0].Size.Width 可以使用宽度,把所有headers宽度的大小去掉,然后一一添加。

    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;
    

    【讨论】:

    • 解决方案呢? OP 似乎想将每个组合框添加到每个列标题,而不是简单地解释为什么他的代码不起作用。
    • 我没有解决办法,因为我仍然不知道他为什么要这么做。如果他能解释他想做什么,我就能提供帮助
    • 我需要一个组合框为列中的每个标题,除了 topLeftHeaderCell
    【解决方案2】:
        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;
    
    
        }
    }
    

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

    【讨论】:

    • 我有一个错误说索引DataGridViewCell.Visible,DataGridViewCell.Size,DataGridViewCell.Test,没有分配,它是只读的
    猜你喜欢
    • 2014-09-11
    • 2017-11-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2013-12-29
    • 1970-01-01
    相关资源
    最近更新 更多