Click here to Skip to main content
15,305,754 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making a small database front end and I have a datagridview that so far I have made to load the contents of my table with the below code.

I now need to make it so that and changes in the datagridview are saved back to the database table.

I want to do this in its own method so that I can easily call it from different places (i want a save button that carries out the method but then also will look to have it save in some other places)

What is the most efficient was of copying the changes in the datagrid view back?

What I have tried:

<pre>private void button1_Click(object sender, EventArgs e)
        {
            //Load Main Table
            SQLiteConnection dbConnectionString;
            dbConnectionString = new SQLiteConnection(@"Data Source = F:\Omega\Drawing Register\DRDB.sqlite; Version = 3");
            dbConnectionString.Open();
            string sql = "SELECT * FROM Jobs";
            SQLiteCommand command = new SQLiteCommand(sql, dbConnectionString);
            var sqlDataAdapt = new SQLiteDataAdapter(sql, dbConnectionString);
            using (DataTable dt = new DataTable())
            {
                sqlDataAdapt.Fill(dt);
                dataGridView1.DataSource = dt;

                //Set Font
                dataGridView1.Font = new Font("MS Sans Serif", 8);
                //Set Column Widths
                dataGridView1.Columns[0].Width = 100;
                //Set Column Names
                dataGridView1.Columns[0].HeaderText = "Enq No";

            }

        }
Posted
Updated 16-Dec-21 23:34pm

1 solution

As you are using DataGridView I have assumed this is WinForms

The most "efficient" way is probably via Data Binding - there are several articles around e.g. A Detailed Data Binding Tutorial[^]
Bind data to DataGridView Control - Windows Forms .NET Framework | Microsoft Docs[^]
   
Comments
Member 15470950 17-Dec-21 6:00am
   
Thank you for the reply.

I might have misunderstood how data binding works, but I want to be in control of when the data is saved back, i was under the impression databinding will save any changes automatically, or have i misunderstood how it works?
CHill60 17-Dec-21 11:00am
   
The Microsoft link gives a specific example of using a Submit button to update the database on request only - search for "dataAdapter.Update" in that page

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900