此代码在运行程序时读取并更新表单,但在我编辑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);
}
}
}
}
程序编译,但更新命令无法在点击button1时更新数据库。
答案 0 :(得分:1)
这看起来很愚蠢,但您是否检查过用于连接的用户名是否具有写入权限而不只是数据库上的只读权限?