程序实现了,批量插入,更新,删除;
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;
using System.Data.SqlClient;
namespace DXApplication3
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SaveChange();
getall();
}
string Add = string.Format(@"server=192.168.60.18;database=浙江先芯科技;uid=sa;pwd=lierda");
DataSet DS=new DataSet();
private void SaveChange()
{
SqlConnection connection = new SqlConnection(Add);
string Select = string.Format(@"SELECT MPN],品牌],[结存数量],[货位号],[ID] FROM [dbo].[备品]");//ID为主键
string Insert = string.Format(@"Insert into [dbo].[备品](MPN,品牌,结存数量,货位号) values(@MPN,@品牌,@结存数量,@货位号)");//不需要主键
string Update = string.Format(@"Update [dbo].[备品] SET MPN=@MPN,品牌=@品牌,结存数量=@结存数量,货位号=@货位号 where ID=@OLDID");
string Delete = string.Format(@"Delete From [dbo].[备品] where ID=@ID");
SqlDataAdapter adapter=new SqlDataAdapter();
SqlCommand command = new SqlCommand(Select,connection);
adapter.SelectCommand = command;
command=new SqlCommand(Insert,connection);//插入不需要主键
command.Parameters.Add("@MPN", SqlDbType.NVarChar, 15, "MPN");
command.Parameters.Add("@品牌", SqlDbType.NVarChar, 15, "品牌");
command.Parameters.Add("@结存数量", SqlDbType.NVarChar, 15, "结存数量");
command.Parameters.Add("@货位号", SqlDbType.NVarChar, 15, "货位号");
adapter.InsertCommand = command;
command = new SqlCommand(Update,connection);//更新需要主键
command.Parameters.Add("@MPN", SqlDbType.NVarChar, 15, "MPN");
command.Parameters.Add("@品牌", SqlDbType.NVarChar, 15, "品牌");
command.Parameters.Add("@结存数量", SqlDbType.NVarChar, 15, "结存数量");
command.Parameters.Add("@货位号", SqlDbType.NVarChar, 15, "货位号");
command.Parameters.Add("@ID", SqlDbType.Int, 15, "ID");
SqlParameter parameter = command.Parameters.Add("@OLDID",SqlDbType.NVarChar,5,"ID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.UpdateCommand = command;
command = new SqlCommand(Delete, connection);//删除需要主键
parameter = command.Parameters.Add("@ID", SqlDbType.NVarChar, 15, "ID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
adapter.Update(DS.Tables[0]);
DS.AcceptChanges();//只提交更改的了的内容
}
private void Form1_Load(object sender, EventArgs e)
{
getall();
}
private void getall()
{
try
{
SqlConnection connection = new SqlConnection(Add);
string Select = string.Format(@"SELECT MPN,品牌,结存数量,货位号,ID FROM [dbo].[备品]");
SqlDataAdapter adapter = new SqlDataAdapter(Select, connection);
adapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
}
实际效果如下图,单击button1。可以实现保存操作!表格最后一行为新增行!<img alt="安静" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/quiet.gif" />