简体   繁体   English

从dataGridView C#comboBox?

[英]C# comboBox from dataGridView?

I want combobox with values from one cell datagridview. 我想使用一个单元格datagridview中的值的组合框。 i try this, but don't work :( any ideas? 我尝试这个,但是不起作用:(任何想法?

            comboBox1.Items.Clear();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                comboBox1.Items.Add(row.Cells[2].Value.ToString());
            }

The Value property is null , and throwing the exception when you call ToString() on it. Value属性为null ,并且在对它调用ToString()ToString()异常。

Check for null first: 首先检查null

if (row.Cells[2].Value != null)
    comboBox1.Items.Add(row.Cells[2].Value.ToString());

Alternatively, use LINQ to iterate through the rows and populate the ComboBox : 或者,使用LINQ遍历各行并填充ComboBox

comboBox1.Items.AddRange(
    dataGridView1.Rows.Cast<DataGridViewRow>()
                 .Where(x => x.Cells[2].Value != null)
                 .Select(x => x.Cells[2].Value.ToString())
                 .ToArray());

I think row.Cells[2].Value has NULL. 我认为row.Cells [2] .Value为NULL。 Try row.Cells[1].Value 尝试row.Cells[1].Value

The row.Cells[i] collection always starts at 0, so depending on how many columns you have, row.Cells[2] is actually the third column, and could be non existent. row.Cells[i]集合始终从0开始,因此,取决于您有多少列, row.Cells[2]实际上是第三列,可能不存在。 However, if that's the case, you'd like end up with a 'System.IndexOutOfRange' exception instead. 但是,在这种情况下,您想以一个'System.IndexOutOfRange'异常结束。

It's more likely that the cell doesn't have anything in it, or that the row doesn't even exist. 单元格中可能没有任何东西,甚至行甚至不存在。 Step through the debugger and see where the error is coming up. 逐步调试器,查看错误发生的位置。

Another, more specific way of handling this would be to specify the range by using a for loop instead: 另一种更具体的处理方法是使用for循环来指定范围:

// Rows.Count specifies the range explicitly - if you have 5 rows, 
// if i <= 5, it will loop through until it increments to 6, then stop.
for(int i = 0; i <= dataGridView1.Rows.Count; i++)
{
    if (dataGridView1.Rows.Cells[2].Value != null)
        comboBox1.Items.Add(dataGridView1.Rows.Cells[2].Value.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM