Export selection from DataGrid to .csv [duplicate]

老子叫甜甜 提交于 2019-12-25 18:25:05

问题


More specific asked question: Export DataBase (.mdb / .accdb) to .csv

Im new to Data Grid and Need to Export specific lines that are marked (selected).

I cant find a easy way to Export only the selected fields.

Code right now without selection:

StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = DataSet_DB.Tables[0].Columns.Cast<DataColumn>().
        
sb.AppendLine(string.Join(";", columnNames));

foreach (DataRow row in DataSet_DB.Tables[0].Columns)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(";", fields));
}

File.WriteAllText(SFD.FileName, sb.ToString());

回答1:


You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Info :

export specific columns




回答2:


You should loop over the DataGrid1.SelectedRows property after setting the required property SelectionMode to FullRowSelect. Then each grid row has a property named DataBoundItem that references the object used to fill the row.
In your case this object seems to be a DataTable so you could reach back the DataRow casting the DataBoundItem first to DataRowView and then getting the DataRow from there.

foreach (DataGridViewRow gridrow in dataGrid1.SelectedRows)
{
    DataRow row = ((gridrow.DataBoundItem) as DataRowView).Row
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(";", fields));
}


来源:https://stackoverflow.com/questions/46784105/export-selection-from-datagrid-to-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!