How to insert data from GridView to Database | 23 Feb 2010 01:02:51 |
| | Hi Experts
I have no of row in DataGridView, now i need when click Save button , i need save all rows in to that database.
I am using vb.net, so kindly help me using some sample code.
Thank you | |
| | | |
| Re:How to insert data from GridView to Database | 23 Feb 2010 01:02:51 |
| | put 2 text box in aspx.vb page
TextBox2.Text
TextBox3.Text
1 gridview
2 buttons
Button3= for add textbox data to gridview
Button4= final save data into database
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dynamic_Bind_Grid()
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
grid bind
Public Sub Dynamic_Bind_Grid()
Dim dt As New DataTable
Dim str As String
Dim ds As New DataSet
'str = "Select Name,Address from TestTable"
'ds = obj.OpenDataSet(str, "dynam122")
Dim col As New DataColumn
Dim row As DataRow
Dim i As Integer
If GridView1.Rows.Count = 0 Then
GridView1.Visible = True
col = dt.Columns.Add("Name")
col = dt.Columns.Add("Address")
row = dt.NewRow
row("Name") = TextBox2.Text
row("Address") = TextBox3.Text
dt.Rows.Add(row)
GridView1.DataSource = dt
GridView1.DataBind()
Button4.Visible = True
Else
GridView1.Visible = True
Button4.Visible = True
dt = Session("Dt")
row = dt.NewRow
row("Name") = TextBox2.Text
row("Address") = TextBox3.Text
dt.Rows.Add(row)
GridView1.DataSource = dt
GridView1.DataBind()
End If
Session("Dt") = dt
End Sub
Save button click event
'Insert data into database
Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim mytrans As SqlTransaction
obj.OpenCN()
Try
Dim i As Integer
Dim dt As New DataTable
dt = Session("Dt")
If GridView1.Rows.Count = 0 Then
Else
For i = 0 To GridView1.Rows.Count - 1
Dim name1 As String = dt.Rows(i).Item(0)
Dim address1 As String = dt.Rows(i).Item(1)
mytrans = obj.cn.BeginTransaction
Dim cmd As New SqlCommand
cmd.Transaction = mytrans
cmd.CommandText = "TestTableInsert"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = obj.cn
'cmd = obj.Proc("TestTableInsert")
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name1
cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = address1
cmd.ExecuteNonQuery()
mytrans.Commit()
Next
End If
GridView1.Visible = False
Button4.Visible = False
dt.Clear()
Session("Dt") = dt
Catch ex As Exception
Throw ex
mytrans.Rollback()
End Try
End Sub
Regards,
Jitendra Patel | |
| | | |
| Re:How to insert data from GridView to Database | 23 Feb 2010 01:02:51 |
| | Yes
Exactly great answer. and when you put code Please mark in green/ blue color of that block.
Thank you | |
| | | |
|