使用LINQ修改SQL Server 数据库数据
案例练习-删除库存商品信息
创建一个Windows应用程序,主要用来删除指定的商品信息。在窗体中添加一个ContextMenyStrip控件,用来作为删除快捷菜单,再添加DataGridView控件,用来显示数据库中的数据。
完整示例代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace LINQDelSql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//定义数据库连接字符串
string strCon = "Data Source=UerDate-pc\\SQL2019;Database=db_Use;Uid=sa;Pwd=123456;";
linqtosqlClassDataContext linq; //声明Linq连接对象
string strID = ""; //记录选中的商品编号
private void Form1_Load(object sender, EventArgs e)
{
BindInfo();
}
private void dgvInfo_CellClick(object sender, DataGridViewCellEventArgs e)
{
//获取选中的商品编号
strID = Convert.ToString(dgvInfo[0, e.RowIndex].Value).Trim();
}
private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (strID == "")
{
MessageBox.Show("请选择要删除的记录");
return;
}
linq = new linqtosqlClassDataContext(strCon);//实例化Linq连接对象
//查找要删除的商品信息
var result = from stock in linq.tb_stock
where stock.tradecode == strID
select stock;
linq.tb_stock.DeleteAllOnSubmit(result); //删除商品信息
linq.SubmitChanges(); //实例化Linq连接对象提交操作
MessageBox.Show("商品信息删除成功");
BindInfo();
}
private void BindInfo()
{
linq = new linqtosqlClassDataContext(strCon); //创建Linq连接对象
//获取所有商品信息
var result = from info in linq.tb_stock
select new
{
商品编号 = info.tradecode,
商品全称 = info.fullname,
商品型号 = info.type,
商品规格 = info.standard,
单位 = info.unit,
产地 = info.produce,
库存数量 = info.qty,
进货时的最后一次进价 = info.price,
加权平均价 = info.averageprice
};
dgvInfo.DataSource = result;//对DataGridView控件进行数据绑定
}
private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}