Insert New Record

R

RN1

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 =
"bobby"
.Parameters.Add("@Subject", SqlDbType.VarChar, 50).Value =
"Physics"
.Parameters.Add("@Marks", SqlDbType.Int).Value = 85
End With

sqlDapter.InsertCommand = sqlCmd
sqlDapter.Update(dSet.Tables("Marks"))

dgMarks.DataSource = dSet.Tables("Marks").DefaultView
dgMarks.DataBind()
End Sub
</script>

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

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.

Thanks,

Ron
 
R

RN1

Hi

before update the datatable just a execure non query

sqlDapter.InsertCommand.ExecuteNonQuery();

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?

Ron
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top