C# 如何将DataGridView中的选定项作为DataTable获取?

C# 如何将DataGridView中的选定项作为DataTable获取?,c#,sql,C#,Sql,我有一个DataGridView,它从DB中获取值。现在,我只想打印出用户从UI中选择的所选项目。如果用户希望在DataGridView中打印整个表,我会这样做: var dataTable=dataGridView1.DataSource作为dataTable 现在我尝试在DataGridView中使用SelectedCells属性。但我还是不明白:-( var selecteditems=dataGridView1.SelectedCells作为DataTable 我在这里做错了什么?我只想

我有一个DataGridView,它从DB中获取值。现在,我只想打印出用户从UI中选择的所选项目。如果用户希望在DataGridView中打印整个表,我会这样做:

var dataTable=dataGridView1.DataSource作为dataTable

现在我尝试在DataGridView中使用SelectedCells属性。但我还是不明白:-(

var selecteditems=dataGridView1.SelectedCells作为DataTable


我在这里做错了什么?我只想将所选单元格放入数据表。

DataGridView.SelectedCells返回给您的是一个集合,而不是数据表

如果希望输出为DataTable,可以克隆表的结构,然后遍历SelectedCells集合

比如:

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);
}
DataTable selected=DataTable.Clone();
对于(int i=0;i
不应该是第二行,比如:

newRow[“column”]=dataGridView.SelectedCells[i]