using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ck
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
public void FrmMain_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“ckDataSet.Goods”中。您可以根据需要移动或删除它。
this.GoodsTableAdapter.Fill(this.ckDataSet.Goods);
}
public void btnQuery_Click(object sender, EventArgs e)
{
string goodsNameStr = txtQuery.Text;
if (goodsNameStr != "")
{
dgvGoods.DataSource = ckDataSet.Goods.Select("GoodsName Like\'" + goodsNameStr + "%\'");
}
else
{
dgvGoods.DataSource = ckDataSet.Goods;
}
}
public void btnSelect_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要删除此行数据吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
DataRow delrow = ckDataSet .Goods .Rows[dgvGoods.SelectedRows[0].Index];
delrow.Delete();
GoodsTableAdapter.Update (ckDataSet.Goods);
ckDataSet.Goods.AcceptChanges();
}
}
}
}
System.InvalidOperationException:“当传递具有已删除行的 DataRow 集合时,Update 要求有效的 DeleteCommand。”
这个怎么解决吖,我照着书上写的但是我一运行就报错,初学者,希望能够帮忙指点指点
测试可用的简单示例如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
conn = new SqlConnection("server=.;uid=test;pwd=123456;database=test;");
Goods = new DataTable();
GoodsTableAdapter = new SqlDataAdapter("select * from goods", conn);
thisBuilder = new SqlCommandBuilder(GoodsTableAdapter);
}
SqlCommandBuilder thisBuilder ;
DataTable Goods;
SqlDataAdapter GoodsTableAdapter;
SqlConnection conn;
public void Form1_Load(object sender, EventArgs e)
{
GoodsTableAdapter.Fill(Goods);
}
public void btnQuery_Click(object sender, EventArgs e)
{
string goodsNameStr = txtQuery.Text;
if (goodsNameStr != "")
{
dgvGoods.DataSource = Goods.Select("GoodsName Like\'" + goodsNameStr + "%\'");
}
else
{
dgvGoods.DataSource = Goods;
}
}
public void btnSelect_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要删除此行数据吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
DataRow delrow = Goods.Rows[dgvGoods.SelectedRows[0].Index];
delrow.Delete();
GoodsTableAdapter.Update(Goods);
Goods.AcceptChanges();
}
}
}
}
数据库和DataGridview都设置了主键
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!