Reputation: 31
I want to pass the colored cell value to the ListBox
. But unfortunately, I can't do this by using the following code.
What I have done wrong?
var cellColorValue = dataGridView1.Rows.Cast<DataGridViewRow>()
.SelectMany(row => row.Cells.Cast<DataGridViewCell>()
.Where(c => c.Style.BackColor == Color.Yellow)
.Select(x => x.Value).ToString()
.ToList());
listBox1.Items.Add(cellColorValue);
Upvotes: 1
Views: 117
Reputation: 4587
So, you are trying to add items in the listbox but you are providing it an List
of items. Which means, you cannot do it with simply calling the Add()
method.
What you should do is, either pass the list cellColorValue
into the AddRange()
method or use a DataSource
object to bind the values.
Do this:
listBox1.Items.AddRange(cellColorValue);
Or
listBox1.DataSource = cellColorValue;
listBox1.DataBind(); // Call this method as well to bind the data source.
UPDATE
I see, your resulting objects is an EInumerable
of objects which the AddRange()
method doesn't accept. I have refactored your LINQ expression as so it is sent to the listbox
accordingly. Assuming that you want to get the cell values of the DataGridView
in your listbox. See:
var cellColorValue = dataGridView1.Rows.Cast<DataGridViewRow>()
.SelectMany(row => row.Cells.Cast<DataGridViewCell>()
.Where(c => c.Style.BackColor == Color.Yellow)
.Select(cell => cell.Value.ToString()))
.ToArray();
And add that into the listbox like this:
listBox1.Items.AddRange(cellColorValue);
Upvotes: 1