gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:56:36 26 4
gpt4 key购买 nike

我想从 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);
}
}
}
}
}

最佳答案

我认为您对 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 类。

关于c# - 将 DataGridView 值插入 MySql 数据库。 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20500469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com