我在datagridview
中显示数据库表。我可以将记录从datagridview
正确保存到sql中的数据库。将编辑的数据保存在行中
现在,我想修改和更改一些记录并将这些更改保存在数据库中。我怎样才能做到这一点?我使用的绑定datasource
附加到数据集datatable
。
private void Form1_Load(object sender, EventArgs e)
{
this.cPDM0020TableAdapter.Fill(this.cpdm_dataset.CPDM0020);
}
private void btnSave_Click(object sender, EventArgs e)
{
string code = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString().ToUpper();
string currency_Name = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString().ToUpper();
string boolBase = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string local_per_Base = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string base_per_Local = dataGridView1[4, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string insert_sql = "INSERT INTO centraldb.dbo.CPDM0020(Code,Currency_Name,Base,Local_per_Base,Base_per_Local)VALUES('" +
code + "','" +
currency_Name + "','" +
boolBase + "','" +
local_per_Base + "','" +
base_per_Local + "')";
if (this.ExecuteSql(insert_sql))
{
MessageBox.Show("Record Inserted Successfully.");
}
else
{
MessageBox.Show("Insert Failed");
}
}
public bool ExecuteSql(string command)
{
SqlCommand sqlCommand = new SqlCommand(command, connection);
connection.Open();
sqlCommand.ExecuteNonQuery();
this.cPDM0020TableAdapter.Fill(this.cpdm_dataset.CPDM0020);
dataGridView1.DataSource = cpdm_dataset.CPDM0020;
sqlCommand.Dispose();
connection.Close();
return true;
}
我可以保存新的条目很容易地在数据库和datagridview
,但保存按钮编辑后,我不能编辑已经存在records..On点击,它再次显示了先前的值。请帮忙。
你不能声明在try块变量,一旦试已经结束,他们将丢失。 – Flater 2013-03-11 13:17:22
另外,神奇宝贝异常处理通常是一个坏主意。 – Flater 2013-03-11 13:18:41
这是我的代码:私人无效Form1_Load的(对象发件人,EventArgs的) { this.cPDM0020TableAdapter.Fill(this.cpdm_dataset.CPDM0020);} – user2156513 2013-03-12 04:26:40