Simple Way to Update Data to Sql-Server Database using Datagridview in C#

Here is a simple way to load and Update data using Datagridview in C#.

1) Drag a datagridview on your form.
2) Drag two buttons one button will be used to load data in the Datagridview and the second would be used to update Data to the Database.
3) In the Global section of the Class i.e After the class name declare the following classes.

SqlConnection connection;
SqlDataAdapter adapter;
 DataTable dt;
In the form Constructor add the following
public Form1()
        {
            InitializeComponent();
            connection = new SqlConnection(Properties.Settings.Default.connectionString);
            connection.Open();
        }


In the Button Load event which would load data into the Dataset Enter the following

private void Button1_Click(object sender, EventArgs e)
        {
             
            string commandText = "select * from blah";
           adapter = new SqlDataAdapter(commandText, connection);
                SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
                dataGridView1.AutoGenerateColumns = true;      
                dt = new DataTable();
                adapter.Fill(dt);
                BindingSource b1 = new BindingSource();
                b1.DataSource = dt;
                dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCells);
                dataGridView1.DataSource = b1;
           
        }

And finally in the Update Button Click Event add the following

private void btnUpdate_Click(object sender, EventArgs e)
        {
                adapter.Update(dt);
                dataGridView1.Refresh();
        }
 
Caution: Remember that the Table Must consist of A PRIMARY KEY otherwise the code will not work.

Happy Programming
 

2 comments:

  1. I apologize in advance, I'm still learning. Your tutorial seems very straight forward, and I appreciate that. My only issue is that adapter only exists in the Button1_Click event. In btnUpdate_Click event it doesn't know what adapter is. How would I fix that?

    ReplyDelete
    Replies
    1. The reference of the adapter is in the global section of the class

      Delete

Running Drupal in Docker

I will assume that you have already installed docker. If you haven't installed docker please visit https://www.docker.com/ to download a...