【发布时间】:2011-06-25 18:48:26
【问题描述】:
此代码在我运行程序时可以正常读取和更新表单,但在我编辑 datagridview 中的值并单击更新时它不会更新。
我正在关注一个视频教程系列,这段代码在视频中确实可以更新表格。
问题:为什么我编辑datagridview中的值时它没有更新?
using System.Data.SqlServerCe;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private SqlCeConnection conn; // Our Connection
private SqlCeDataAdapter da; // Data Adapter
private DataSet ds; // Dataset
private string sTable = "authors"; // Table Name
public Form1()
{
InitializeComponent();
InitData(); // Get the Data
dataGridView1.DataSource = ds;
dataGridView1.DataMember = sTable;
}
public void InitData()
{
try
{
// Instantiate the Connection
conn = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
// Instantiate a new DataSet
ds = new DataSet();
// init SQLDataAdapter with select command and connection
da = new SqlCeDataAdapter("SELECT id, name, email FROM " + sTable, conn);
// Automatically generates insert, update and delete commands
SqlCeCommandBuilder cmdBldr = new SqlCeCommandBuilder(da);
// Fill in the dataset view
da.Fill(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show("Exception: " + excep.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
da.Update(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
}
}
}
程序已编译,但更新命令无法在单击按钮1 时更新数据库。
【问题讨论】:
-
我会检查更新命令是否已经初始化。这可能吗?
-
我该怎么做?,我自己没有初始化任何更新命令,
-
在代码中的 da.Update 行放置一个断点,将鼠标悬停在 ds 上,然后检查您期望的更新。我认为数据集不会知道界面上所做的任何更改。
标签: c# sql visual-studio-2010 datagridview sql-server-ce