【发布时间】:2016-04-05 16:34:30
【问题描述】:
我有下面的代码,我试图从 Windows 应用程序中所做的 c# 网格视图更改更新数据库....
代码未更新 SQL Server 数据库。我不确定问题到底发生在哪里。一切似乎都很好......
或者有没有办法再次使用“更新查询语句”来更新数据库表,重点是如何为数据网格视图中的任何值更改编写更新语句?
我认为绑定和选择命令语句可能存在问题...
谁能指出我解决这个问题的正确方向?
public partial class KnowledgeBaseForm : Form
{
private SqlDataAdapter SDA = new SqlDataAdapter();
private DataTable DT = new DataTable();
private void button_retrievekb_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter SDA = new SqlDataAdapter(@"SELECT * From Table1", con);
SDA.Fill(DT);
bindingsource.DataSource = DT;
dataGridView.DataSource = bindingsource;
if (DT.Rows.Count > 0)
{
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Knowledge Base Rules Found");
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//binding the datasource with the changes made in the gridview
bindingsource.DataSource = dataGridView.DataSource;
DT.AcceptChanges();
scb = new SqlCommandBuilder(SDA);
SDA.Update((DataTable) bindingsource.DataSource);
MessageBox.Show("Updates successfully submitted to CoSD");
}
}
}
【问题讨论】:
-
在类根中声明您的 DT 对象,如您的 DataAdapter,并在调用 SDA.Update 之前使用 DT.AcceptChanges,测试它,如果它有效,现在让我们来
-
嗨...我已经按照你说的编辑了代码...但仍然没有工作...
标签: c# winforms datagridview windows-applications sqldataadapter