sean
sean

Reputation: 9268

Saving Data in Data Grid View to MySQL

I am new in creating application using Visual Studio 2010 C#. I am creating an application where the user will input data in a data grid view in C# and automatically save it in MySQL.

I have this code to save the data from a textbox:

private void buttonSaveEmployee_Click(object sender, EventArgs e)
    {
        string MyConString = "SERVER=localhost;" + "DATABASE=payroll;" + "UID=root;" + "PASSWORD=admin;";
        MySqlConnection connection = new MySqlConnection(MyConString);
        MySqlCommand command = connection.CreateCommand();
        command.Connection = connection;
        using (MySqlConnection conn = new MySqlConnection(MyConString))
        {
            connection.Open();
            using (MySqlCommand com = connection.CreateCommand())
            {
                command.CommandText = "insert into employee(employee_lastname) values(?employee_lastname)";
                command.Parameters.Add(new MySqlParameter("?employee_lastname", MySqlDbType.VarChar));
command.Parameters["?employee_lastname"].Value = textBoxEmpLastName.Text;
                command.ExecuteNonQuery();
            }
        }
    }

I am wondering if this is the code to save a data from a textbox, how can I save the data from data grid view to MySQL. Any help will be much appreciated. Thanks.

Upvotes: 0

Views: 7255

Answers (1)

Michael D. Irizarry
Michael D. Irizarry

Reputation: 6302

You should bind your datagrid to the database thru its DataSource property this way any changes done to the grid will be reflected in the database.

Example

MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter("select * from employee", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];

So it would be as easy as calling

mySqlDataAdapter.Update(DS.Tables[0]);

Upvotes: 2

Related Questions