问题
What I must do:
I Need to load a Database, search entries and Export the selected columns.
The Problem:
I got a DataGrid
(no DataGridView
) for list and select the Database entries and I cant get any solution to Export only the selected rows with ;
as seperator.
Code how I load and list the DataBase
using (OleDbConnection ODC = new OleDbConnection("Provider = Microsoft.Jet.OLEDB." + iOledDBVersion + "; Data Source = " + connectionString))
{
OleDbCommand ODCmd = new OleDbCommand(insertSQL);
ODCmd.Connection = ODC;
ODC.Open();
ODCmd.ExecuteNonQuery();
//Data-Adapter erstellen
OleDbDataAdapter OleDbDataAdapter_Temp = new OleDbDataAdapter(insertSQL, ODC);
OleDbCommandBuilder OleDbCommandBuilder_Temp = new OleDbCommandBuilder(OleDbDataAdapter_Temp);
//Daten aus der Datenbank in Dataset speichern
OleDbDataAdapter_Temp.Fill(DataSet_DB, sTabelle);
// Schleife für jede Tabelle
for (int i = 0; i < DataSet_DB.Tables.Count; i++)
{
// Setzt die Spalten der DB in das DataGrid
DataGrid_Table.DataContext = DataSet_DB.Tables[i].DefaultView;
}
}
Is there any propper way of exporting those rows?
回答1:
There is a SelectedItems
property that will return the selected items in the DataGrid
. In your case you could each such item to a DataRowView
, e.g.:
StringBuilder sb = new StringBuilder();
foreach(var selectedRow in DataGrid_Table.SelectedItems.OfType<DataRowView>())
{
foreach(DataColumn column in selectedRow.DataView.Table.Columns)
{
sb.Append(selectedRow[column.ColumnName] + ";");
}
sb.Append(Environment.NewLine);
}
string export = sb.ToString();
来源:https://stackoverflow.com/questions/46786872/export-database-mdb-accdb-to-csv-with-row-selection