日期:2014-05-20  浏览次数:20748 次

各种方法都用了,可就是无法更新数据库
SqlConnection   myConnection   =   new   SqlConnection(@ "连接字符串 ");
SqlDataAdapter   myAdapter   =   new   SqlDataAdapter( "select   *   from   Customer ",   myConnection);
SqlCommandBuilder   mybuilder   =   new   SqlCommandBuilder(myAdapter);
DataSet   myDataset   =   new   DataSet();
myAdapter.Fill(myDataset,   "Customer ");
myAdapter.UpdateCommand   =   mybulider.GetUpdateCommand();       //这句话是后加的,也无法更新
myAdapter.Update(myDataset,   "Customer ");
myDataset.Tables[0].AcceptChanges();
现在是在一个窗体的datagridveiw和数据库的表绑定,我在窗体的load事件里绑定的,窗体只有一个按钮,上面是这个按钮的click事件代码,怎么就不能更新呢?
数据库用的是.net2005自带的sql2005,就存放在本程序文件夹下,连接都正常,可就是更新不了,哪为高人能给解释一下

------解决方案--------------------
你的Customer表有没有主键? 有主键的话没下面这行也能更新
myAdapter.UpdateCommand = mybulider.GetUpdateCommand(); //这句话是后加的,也无法更新
------解决方案--------------------
给你一个例子吧.测试通过,前两天写的,也是别人问的..


核心就是SqlDataAdapter+SqlCommandBuilder+BindingSource...

写了个简单的例子,测试通过:

两个按钮,一个 "加载 ",一个 "更新 ",还有一个 "DataGridView "

using System.Data;
using System.Data.SqlClient;

namespace DataGridViewUpdateToDataBase
{
public partial class Form1 : Form
{
private SqlDataAdapter sda = new SqlDataAdapter();
private BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
}

//加载
private void btnLoad_Click(object sender, EventArgs e)
{
DataBind();
}

//数据绑定
private void DataBind()
{
SqlConnection con = new SqlConnection( "server=.;database=student;uid=sa;pwd=0421 ");
sda = new SqlDataAdapter( "select * from studentDetails ", con);
SqlCommandBuilder buider = new SqlCommandBuilder(sda);
DataSet ds = new DataSet();
sda.Fill(ds, "student ");
bs .DataSource =ds.Tables [ "student "];
this.dataGridView1.DataSource = bs;
}

//更新
private void btnUpdate_Click(object sender, EventArgs e)
{
sda.Update((DataTable)bs.DataSource);
}
}
}



------解决方案--------------------
vb.net中
myAdapter.Fill(myDataset, "Customer ")
myAdapter.UpdateCommand.connection.close()
myAdapter.UpdateCommand.connection.open()
就可以了,也就是说执行sql用的连接断开一下!
vc.net中不清楚!
不妨去试试!