简体   繁体   中英

How to update a database using DataGrid C# WPF?

I want to update a database (SQLite) with the dataGrid. I can change values in the dataGrid but changes don't apply to the database that why I want to add a button "save" to save all changes applied in the dataGrid,

I searched about the problem but I couldn't find an answer

this is my C# code to fill the DataGrid:

SQLiteConnection sQLiteConnection = new SQLiteConnection("Data source = dataSet.db ; version = 3 ;");
        SQLiteCommand sQLiteCommand; 
        SQLiteDataAdapter sQLiteDataAdapter; 
        System.Data.DataTable dataTable = new System.Data.DataTable("Naamaa");
        SQLiteCommandBuilder cmd;
        DataSet ds;
        public ManipulateData(string wilaya, int theme)
        {
            InitializeComponent();

            try
            {
                sQLiteConnection.Open();
                sQLiteCommand = new SQLiteCommand(sQLiteConnection);
                sQLiteCommand.CommandText = "SELECT * FROM " + wilaya + " ;";
                sQLiteCommand.ExecuteNonQuery();
                sQLiteDataAdapter = new SQLiteDataAdapter(sQLiteCommand);
                sQLiteDataAdapter.Fill(dataTable);

                McDataGrid.ItemsSource = dataTable.DefaultView;


            }catch
            {
                MessageBox.Show("Error");
            }
        }

and this is the xaml code :

<Grid Background="White">
        <DataGrid x:Name="McDataGrid"  />
</Grid>

I'm working on something quite similar at the moment, only that I'm using Postgres.

One easy way to do this is set the DataGridView.ReadOnly property to true, then when user selects a row in DataGridView, you can launch a Windows Form with all the data in from that selected row and a "Save" button to update data in DataBase. Then from that button you only need to launch an update query to database with data collected from the form.

If you want to modify data on the DataGridView itself, things get more complex as you need to keep track of which rows have been edited on DataGridView (unless you don't care about optimization and can just do an update for every single row, no matter if it has been edited or not). You can use a list of DataGridViewRow for all modified rows.

Was that understandable? Not very used to write english, specially on quite complex matters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM