【问题标题】:Add items to combobox in an already existing datagridview comboBox column将项目添加到现有 datagridview 组合框列中的组合框
【发布时间】:2017-05-27 12:14:51
【问题描述】:

我的 Windows 窗体应用程序中有一个 datagridview。 datagridview 有 3 列。第一列是组合框。 我正在尝试将项目添加到组合框,但它正在工作。 这是代码(C#语言)

    foreach (int counter=0; counter<5; counter++ )
        {
        this.dataGridView1.Rows.Add();

        DataGridViewComboBoxCell cbCell = new DataGridViewComboBoxCell();
        cbCell.Items.Add("Male");
        cbCell.Items.Add("Female");                 
        dataGridView1.Rows[counter].Cells[0] = cbCell;

        dataGridView1.Rows[counter].Cells[1].Value = firstname[counter];

        dataGridView1.Rows[counter].Cells[2].Value = lastname[counter];                    

    }

网格显示 5 行。但是第一个组合框列在其中的每个组合框中都没有项目。

请帮忙。 谢谢。

【问题讨论】:

    标签: datagridviewcombobox datagridviewcomboboxcell


    【解决方案1】:

    由于代码没有显示列的构造方式,因此很难判断问题可能是什么,但是代码没有使用DataGridViewComboBoxColum。 DataGridViewComboBoxColumn 是您只需将第 0 列中的每一行都设置为包含“男性”、“女性”选项的组合框。

    格式错误的foreach 循环不正确,无法编译。我假设 for 循环是您正在寻找的。在这个for 循环之后……一个新行被正确地添加到网格中。然后创建一个新的DataGridViewComboBoxCell 并添加当前行的单元格[0]。 dataGridView1.Rows[counter].Cells[0] = cbCell;。这个单元格[0] 被添加到每个新行中。

    如果DataGridViewViewComboBoxColumn 设置正确,这是不必要的。添加DataGridViewComboBoxCell 是完全有效的,基本上允许您将组合框放入任何“单个”单元格中。但是,如果以这种方式使用,组合框本身的使用就会产生问题。

    循环将数据“添加”到dataGridView1。当您阅读数据时,似乎缺少有关“性别”(男性,女性)的部分,因此该值未设置为其他值。示例:没有像下面这样的一行:

    dataGridView1.Rows[counter].Cells[0].Value = gender[counter];
    

    如果存在保存此信息的“性别”数组,那么当代码在组合框列上方的代码行中设置此值(男性、女性)时,将自动将组合框选择设置为该值。数据将只是两个值中的“一”(1)个。

    假设这就是您要查找的内容,下面的代码演示了如何使用DataGridViewComboBoxColumn

    将数据读入组合框单元格时要注意;如果组合框列的字符串数据与组合框项列表中的一项不匹配,则如果未捕获和处理,代码将崩溃。如果该值为空字符串,则组合框会将所选值设置为空。

    // Sample data
    string[] firstname = { "John", "Bob", "Cindy", "Mary", "Clyde" };
    string[] lastname = { "Melon", "Carter", "Lawrence", "Garp", "Johnson" };
    string[] gender = { "Male", "", "Female", "", "Male" };
    // Create the combo box column for the datagridview
    DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
    comboCol.Name = "Gender";
    comboCol.HeaderText = "Gender";
    comboCol.Items.Add("Male");
    comboCol.Items.Add("Female");
    // add the combo box column and other columns to the datagridview
    dataGridView1.Columns.Add(comboCol);
    dataGridView1.Columns.Add("FirstName", "First Name");
    dataGridView1.Columns.Add("LastName", "Last Name");
    // read in the sample data
    for (int counter = 0; counter < 5; counter++ )
    {
      dataGridView1.Rows.Add(gender[counter], firstname[counter], lastname[counter]);
    }
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢 JohnG
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多