SSJ
SSJ

Reputation: 25

C# comboBox from dataGridView?

I want combobox with values from one cell 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());
            }

Upvotes: 0

Views: 309

Answers (3)

Grant Winney
Grant Winney

Reputation: 66439

The Value property is null, and throwing the exception when you call ToString() on it.

Check for null first:

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:

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

Upvotes: 1

Ben
Ben

Reputation: 2523

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. However, if that's the case, you'd like end up with a 'System.IndexOutOfRange' exception instead.

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:

// 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());
}

Upvotes: 0

Vladislav Vazhenin
Vladislav Vazhenin

Reputation: 349

I think row.Cells[2].Value has NULL. Try row.Cells[1].Value

Upvotes: 0

Related Questions