将数据从datagridiew保存到sql server 2008 [英] saving data from datagridiew into sql server 2008
本文介绍了将数据从datagridiew保存到sql server 2008的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hii,
我想知道如何将数据从datagridview(包含未绑定和绑定的列)保存到数据库中.我正在使用Visual Studio 2010(vb.net)..
请帮忙.. !!!
在此先感谢
Hii,
I would like to know how to save the datas from a datagridview(contains both unbound and bound columns) into the database. i am using Visual Studio 2010 (vb.net)..
Please Help..!!!
Thanks in advance
推荐答案
你好Cluelesssssssss,
由于我没有网格和表格结构.我将通过我考虑的示例给出解决方案.
在这里
情况:
我们需要添加/更新员工信息,关键是员工ID.
数据库结构:
表格:
Hello Cluelessssssss ,
Since I didn''t have you grid and table structure. I will be giving solutions through my considered example.
Here it is
Situation :
We need to Add / Update employee information and key is employee id.
Database Stucture :
Table :
/****** Object: Table [dbo].[Employee] Script Date: 01/21/2012 16:38:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Employee](
[Id] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Name] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Position] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Location] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
存放程序:
Store Procedure :
CREATE PROCEDURE sp_SaveEmployeeDetail
( @Id NVARCHAR(10),
@Name NVARCHAR(255),
@Position NVARCHAR(255),
@Location NVARCHAR(255)
)
AS
BEGIN
If EXISTS (SELECT * FROM Employee WHERE Id=@Id)
Begin
Update Employee
SET
Name=@Name ,
Position=@Position ,
Location=@Location
WHERE Id=@Id
End
Else
Begin
Insert Into Employee SELECT @Id,@Name,@Position,@Location
End
END
这是vb.net来调用此过程,该过程将接受参数.
And here is vb.net to call this procedure which would accept parameters .
Dim connection As SqlConnection = New SqlConnection("Data Source=MDT765\MDT765;Initial Catalog=TST;User Id=user;Password=user@123;")
connection.Open()
Dim Cou As Integer
Dim command As SqlCommand = _
New SqlCommand("sp_SaveEmployeeDetail", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@Id", SqlDbType.NVarChar,10)
command.Parameters.Add("@Name", SqlDbType.NVarChar, 255)
command.Parameters.Add("@Position", SqlDbType.NVarChar, 255)
command.Parameters.Add("@Location", SqlDbType.NVarChar, 255)
For Cou = 0 To DataGridView1.Rows.Count - 2
command.Parameters("@Id").Value = DataGridView1.Item(0, Cou).Value.ToString()
command.Parameters("@Name").Value = DataGridView1.Item(1, Cou).Value.ToString()
command.Parameters("@Position").Value = DataGridView1.Item(2, Cou).Value.ToString()
command.Parameters("@Location").Value = DataGridView1.Item(3, Cou).Value.ToString()
command.ExecuteNonQuery()
Next
MsgBox("Done")
您可以在插入数据(行)或在datagridview中编辑数据后更新数据库.
请参阅此提示
使用DataGridView更新数据库
You can update database after inserting data(rows) or edit data in datagridview.
see this tip
DataBase Updation With DataGridView
这篇关于将数据从datagridiew保存到sql server 2008的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文