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 :
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
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")