Export DataBase (.mdb / .accdb) to .csv with row selection

寵の児 提交于 2019-12-02 23:14:23

问题


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

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