Insert New Record



This is how I am trying to insert a new record in a database table &
then display all the records (including the newly inserted record) in
a DataGrid:

<script runat="server">
Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim dSet As DataSet
Dim dTable As DataTable
Dim sqlCmd As SqlCommand
Dim sqlConn As SqlConnection
Dim sqlDapter As SqlDataAdapter

sqlConn = New SqlConnection(".....")
sqlDapter = New SqlDataAdapter
sqlCmd = New SqlCommand("SELECT * FROM TestMarks", sqlConn)
sqlDapter.SelectCommand = sqlCmd

dSet = New DataSet
sqlDapter.Fill(dSet, "Marks")

dTable = New DataTable
dTable = dSet.Tables("Marks")

sqlCmd = New SqlCommand("INSERT INTO TestMarks (UserID,
Subject, Marks) VALUES (@UserID, @Subject, @Marks)", sqlConn)
With sqlCmd
.Parameters.Add("@UserID", SqlDbType.VarChar, 50).Value =
.Parameters.Add("@Subject", SqlDbType.VarChar, 50).Value =
.Parameters.Add("@Marks", SqlDbType.Int).Value = 85
End With

sqlDapter.InsertCommand = sqlCmd

dgMarks.DataSource = dSet.Tables("Marks").DefaultView
End Sub

<form runat="server">
<asp:DataGrid ID="dgMarks" runat="server"/>

But the above code doesn't insert the new record in the DB table.
What's wrong with the above code? Why isn't the new record getting
inserted in the DB table?

Please note that I am aware that there are alternate ways to insert
records; so please do not suggest alternate ways. All I did like to
know is what's wrong with the above code.





before update the datatable just a execure non query


try it...

Best of luck

Thanks Munna for the solution. You are right......ExecuteNonQuery did
the trick but the DataGrid doesn't display the newly inserted record.
Why so?


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads