Casting a datagridview

oshirowanen

I have the following code:

foreach (DataGridViewRow row in dataGridView1.SelectedCells)
{
    textBox1.Text += row.Cells[1].Value;
}

You can probably tell that I am trying to loop through a particular column based on the selected rows of the dataGridView. But it's giving me an error on the following line:

foreach (DataGridViewRow row in dataGridView1.SelectedCells)

The error is:

Additional information: Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.DataGridViewRow'.
TaW

Either use

 foreach (DataGridViewRow row in dataGridView1.SelectedRows)

or, if you need to get at the row from the selected cells:

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
   DataGridViewRow row = dataGridView1.Rows[cell.RowIndex];
   ..
}

In your case the first solution seems to be right, (just like Aaron wrote it.)

Note that both solutions have one or two problems:

The first solution will not get the natural sort order, unless the users take care to follow the weird rules of windows selections..

Use this to solve that problem:

var selectedRowsOrdered = DGV.SelectedRows.Cast<DataGridViewRow>().OrderBy(c => c.Index);

foreach (DataGridViewRow row in selectedRowsOrdered ) textBox1.Text += row[1].Value;

In the second solution, using the SelectedCells collection, you in addition also may have duplicates.

Use this little Linq to get rid of them as well:

var selectedRowsOrdered = DGV.SelectedCells.Cast<DataGridViewCell>()
                         .Select(c => c).OrderBy(c => c.RowIndex).GroupBy(c => c);

foreach (DataGridViewRow row in selectedRowsOrdered ) textBox1.Text += row[1].Value;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related