将DataGridView值插入MySql数据库。 C#

时间:2013-12-10 16:55:56

标签: c# mysql visual-studio-2012 datagridview

我想从dataGridView1向MySql数据库添加新值。代码本身似乎是正确的,Visual Studio 2012中没有错误,但我的数据库中没有插入数据。 这是我正在使用的代码:

private void button2_Click(object sender, EventArgs e)
{
   confirm exec = new confirm();      
}

public class confirm
{
   public void method(DataGridViewCellEventArgs f)
   {
      DataGridView dataGridView1 = new DataGridView();
      Label label1 = new Label(); // contains User ID which is used for payer_code
      Label label6 = new Label(); // contains current dayTime

      foreach (DataGridViewRow row in dataGridView1.Rows)
      {
         if ((bool)dataGridView1.Rows[f.RowIndex].Cells["paidDataGridViewTextBoxColumn"].Value == true)
         {
            try
            {
               string MyConnectionString = "Server=localhost; Database=contractsdb; Uid=root; Pwd=";
               MySqlConnection connection = new MySqlConnection(MyConnectionString);
               MySqlCommand cmd = new MySqlCommand();
               cmd = connection.CreateCommand();
               connection.Open();
               cmd.CommandText = "INSERT INTO payments(pay_name, pay_code, payer_code, pay_sum, pay_date)VALUES(@pay_name, @pay_code, @payer_code, @pay_sum, @pay_date)";
               cmd.Parameters.AddWithValue("@pay_name", dataGridView1.Rows[f.RowIndex].Cells["contractnameDataGridViewTextBoxColumn"].Value);
               cmd.Parameters.AddWithValue("@pay_code", dataGridView1.Rows[f.RowIndex].Cells["contractcodeDataGridViewTextBoxColumn"].Value);
               cmd.Parameters.AddWithValue("@payer_code", label1.Text);
               cmd.Parameters.AddWithValue("@pay_sum", dataGridView1.Rows[f.RowIndex].Cells["sumDataGridViewTextBoxColumn"].Value);
               cmd.Parameters.AddWithValue("@pay_date", label6.Text);
               cmd.ExecuteNonQuery();
               connection.Close();
            }   

            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
            }
         }
      }
   }
}

1 个答案:

答案 0 :(得分:0)

我认为你误解了一些关于OOP的事情。这样做:

您的confirm类方法也应该引用datagridview1(您正在创建一个空的datagridview,因此它永远不会进入foreach循环)

public void method(DataGridView datagridview1) //remove your first argument, you don't need it anymore
{
    //delete the line "DataGridView dataGridView1 = new DataGridView();"
    //and keep the rest of the code as it is
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if(row.Cells["paidDataGridViewTextBoxColumn"].Value == true) //it will check every row, and you don't need "DataGridViewCellEventArgs" argument now
        {
            try
            {
                //your code, it will be same here
            }
        }
}

用于调用方法:

(使用与您相同的button_click事件)

private void button2_Click(object sender, EventArgs e)
{
    confirm exec = new confirm();      
    exec.method(datagridview1); //pass "datagridview1" reference
}

它会将原始datagridview1的引用传递给confirm类。