Insert New Record

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • RN1

    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("SEL ECT * FROM TestMarks", sqlConn)
    sqlDapter.Selec tCommand = sqlCmd

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

    dTable = New DataTable
    dTable = dSet.Tables("Ma rks")

    sqlCmd = New SqlCommand("INS ERT INTO TestMarks (UserID,
    Subject, Marks) VALUES (@UserID, @Subject, @Marks)", sqlConn)
    With sqlCmd
    .Parameters.Add ("@UserID", SqlDbType.VarCh ar, 50).Value =
    "bobby"
    .Parameters.Add ("@Subject", SqlDbType.VarCh ar, 50).Value =
    "Physics"
    .Parameters.Add ("@Marks", SqlDbType.Int). Value = 85
    End With

    sqlDapter.Inser tCommand = sqlCmd
    sqlDapter.Updat e(dSet.Tables(" Marks"))

    dgMarks.DataSou rce = dSet.Tables("Ma rks").DefaultVi ew
    dgMarks.DataBin d()
    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
  • Munna

    #2
    Re: Insert New Record

    Hi

    before update the datatable just a execure non query

    sqlDapter.Inser tCommand.Execut eNonQuery();

    try it...


    Best of luck

    -------
    Munna




    Comment

    • RN1

      #3
      Re: Insert New Record

      On Aug 5, 11:37 am, Munna <munna...@gmail .comwrote:
      Hi
      >
      before update the datatable just a execure non query
      >
      sqlDapter.Inser tCommand.Execut eNonQuery();
      >
      try it...
      >
      Best of luck
      >
      -------
      Munna
      >
      https://www.munna.shatkotha.com/blog....shatkotha.com
      Thanks Munna for the solution. You are right......Exec uteNonQuery did
      the trick but the DataGrid doesn't display the newly inserted record.
      Why so?

      Ron

      Comment

      • Munna

        #4
        Re: Insert New Record

        Hi,

        First insert the data and then fill the dataset...

        Best of luck

        -------
        Munna




        Comment

        Working...