private void 商店一_商品_Load(object sender, EventArgs e)
{
sqlConn = new SqlConnection("Data Source=ASUS-PC\\SQLEXPRESSInitial Catalog=SUPERMARKETIntegrated Security=True")
/SqlConnection连接到本地服务器ASUS-PC,数据库SUPERMARKET,使用windows身份验证
sqlDa = new SqlDataAdapter("SELECT * FROM dbo.商店一_商品", sqlConn)
//Sql适配器以从表dbo.商店一_商品选择所有列作为命令,绑定到SqlConnection
sqlDs = new DataSet()//为数据集分配内存
sqlDa.Fill(sqlDs, "dbo.商店一_商品")//适配器填充到数据集中的表"dbo.商店一_商品"
dataGridView1.DataSource = sqlDs.Tables["dbo.商店一_商品"]
//dataGridView1以数据集中的表"dbo.商店一_商品"作为其数据源
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(sqlDa)
//然后用SqlCommandBuilder自动为SqlDataAdapter生成Insert、Update、Delete命令
}
点button1批量更新到数据库:
private void button1_Click_1(object sender, EventArgs e)
{
if (sqlDs.HasChanges())//如果数据集因我们对datagridview的 *** 作发生改变
{
try//捕获异常
{
sqlDa.Update(sqlDs.Tables["dbo.商店一_商品"])//以数据集的"dbo.商店一_商品"表更新数据库
sqlDs.Tables["dbo.商店一_商品"].AcceptChanges()//接受对数据的修改
MessageBox.Show("更新成功!", " *** 作结果", MessageBoxButtons.OK, MessageBoxIcon.Information)//d出提示更新成功
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "更新失败!", MessageBoxButtons.OK, MessageBoxIcon.Error)
//出现异常提示更新失败
}
}
}
button2删除当前行:
private void button2_Click_1(object sender, EventArgs e)
{ //删除首先要定位到当前选中的记录
int delRowIndex = dataGridView1.CurrentRow.Index
this.dataGridView1.Rows.RemoveAt(delRowIndex)
//然后调用button1更新数据库的方法
button1.PerformClick()
}
'关键是OleDbCommandBuilder(你自己把其改成SqlClient.SqlCommandBuilder)
'以下是我现成的 *** 作OLEDB数据库的,也就是Access2003那种,你自己修改成SQL的就可以用'首先在窗体上加DataGridView1,BindingSource1,BindingNavigator1,Button1控件各一个,然后在BindingNavigator1控件上增加一个按钮ToolStrip_Save
修改的关键是OleDbCommandBuilder(你自己把其改成SqlClient.SqlCommandBuilder)
'--------下面是整个类代码-----------------------------------------------------------
Imports System.Data.OleDb
Public Class Form1
Dim ds As DataSet
Dim tb As DataTable
Dim ap As OleDbDataAdapter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click '手动显示
Me.DataGridView1.AllowUserToAddRows = False
tb = New DataTable
ap = New OleDbDataAdapter("select * from electic ", cn)'这里是SQL命令,Cn是数据库连接,修改成你的Conn
ap.Fill(tb)
Me.BindingSource1.DataSource = tb
Me.BindingNavigator1.BindingSource = Me.BindingSource1
Me.DataGridView1.DataSource = Me.BindingSource1
End Sub
Private Sub ToolStrip_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStrip_Save.Click '调用保存
Save_Data()
End Sub
Private Function Save_Data() As Boolean '保存数据库的 *** 作
Try
Me.DataGridView1.EndEdit()
Me.BindingSource1.EndEdit()
Dim bd As New OleDbCommandBuilder(ap)
ap.UpdateCommand = bd.GetUpdateCommand
ap.Update(Me.BindingSource1.DataSource)
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Private Sub ToolStrip_Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStrip_Cancel.Click '撤销 *** 作
Button1_Click(sender, e)
End Sub
End class
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)