datagridview中事务的问题,“事务不是与当前连接无关联,就是已完成”
小弟在form里就放了一个datagridview和一个button
想利用datagridview实现对表的直接修改,但是现在只能添加行不能修改,修改就提示“事务不是与当前连接无关联,就是已完成”
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlDataAdapter adapter;
DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection sqlconn = new SqlConnection("Server=.;DataBase=user;uid=sa;pwd=sa");
try
{
//select语句中一定要包含主键字段,否则无法更新
adapter = new SqlDataAdapter("select stuno'学号',stuname'姓名' from stuinf", sqlconn);//表里就两个字段,stuno和stuname
adapter.Fill(ds, "student");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds.Tables["student"];
sqlconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "异常错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Server=.;DataBase=user;uid=sa;pwd=sa");
SqlCommandBuilder sBuilder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = sBuilder.GetUpdateCommand();
conn.Open();
SqlTransaction Trans = conn.BeginTransaction();
try
{
adapter.UpdateCommand.Transaction = Trans;
adapter.Update(ds, "student");
Trans.Commit();
}
catch (Exception ex)
{
Trans.Rollback();
MessageBox.Show(this, ex.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
ds.Clear();
adapter.Fill(ds, "student");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds.Tables["student"];
MessageBox.Show(this, "确定", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "异常错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
请各位告诉指教
------解决方案--------------------
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Server=.;DataBase=user;uid=sa;pwd=sa");
//......
adapter.UpdateCommand.Transaction = Trans;
adapter.Update(ds, "student");
Trans.Commit();
}