0

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.

1 Answer 1

2

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Same problem of @BrockHensley

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.