0
votes

I have a DataGridView which takes values from the DB. Now I want to print out only the Selected Items which user has selected from the UI. This is what I did if the user wants to print out whole table in DataGridView:

var dataTable = dataGridView1.DataSource as DataTable;

Now I am trying to use the SelectedCells property in DataGridView. Cant get it though :-(

var selecteditems = dataGridView1.SelectedCells as DataTable;

What I am doing wrong here? All I want is to put my selected cells into a DataTable.

2

2 Answers

0
votes

DataGridView.SelectedCells returns to you a collection, not a DataTable unfortunately.

If you want output as a DataTable, you could clone the structure of the table. Then, iterate through the SelectedCells collection.

Something like:

DataTable selected = dataTable.Clone();
for (int i = 0; i < dataGridView.SelectedCells.Count; i++)
{
     DataRow newRow = selected.NewRow();
     // may have to format below value
     datarow["column"] = dataGridView.SelectedCells[i];
     selected.Rows.Add(newRow);
}
0
votes

Shoudnt be the second last line something like this:

newRow["column"] = dataGridView.SelectedCells[i];