我的DataGridview出了问题:按下一个带有以下代码的按钮,我可以在MySql-Database中保存一些值:
代码
private void button8_Click(object sender, EventArgs e)
{
string connStr = "datasource=localhost;port=3306;username=root;password=123";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "select *from test.edata ;";
MySqlDataAdapter da = new MySqlDataAdapter(sql,conn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
MySqlCommand insertCmd =cb.GetInsertCommand().Clone();
insertCmd.CommandText = insertCmd.CommandText +";SELECT last_insert_id() AS id";
insertCmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
da.InsertCommand = insertCmd;
cb.DataAdapter = null;
DataTable dt = new DataTable();
da.Fill(dt);
DataRow row = dt.NewRow();
row["Familienname"] = "Mustermann";
row["Eid"] = "1";
row["Vorname"] = "Max";
row["age"] = "20";
dt.Rows.Add(row);
da.Update(dt);
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
问题:只要表单关闭,或者每次按下按钮,我都可以在数据库中保存完整的DataGridView吗?我不想用我的代码插入值。应从单元格中读取值。因此,用户可以在UI上更改某些内容,如果他关闭表单,则Gridview将保存在MySql-Database中。
我知道这个网站不是“我的代码”网站,但我确定有一种方法可以在我的MySql-Database中插入所有值!
提前致谢!
编辑我找到了这个链接:MysqlLINK但示例程序仍无效。
答案 0 :(得分:0)
好的,我几乎解决了这个问题:
<强>代码强>
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e) { string id = dt.Rows[e.RowIndex]["Eid"] + ""; string col = dt.Columns[e.ColumnIndex].ColumnName; string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `test`.`edata` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=123"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
private void Form4_Load(object sender, EventArgs e) { dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=123"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from test.edata ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = true;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
}
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
我真的很抱歉这个问题!愿它帮助另一个人!谢谢大家的时间!我不会自己删除这个震撼! :)我希望有人会给这个答案一个很好的评价。无论如何,谢谢你,如果你试图解决这个问题,并祝你有愉快的一天! :)