开发者

Textbox not displaying correctly

Based off this VB code I'm getting everything to create correctly within my SQL database but instead of the Food_ID displaying in the txtfoodid it's popping up in a message box (I think it's because of the Try/Catch).

 Dim con As New OleDbConnection(DBcon)
    Try
        Dim dr As OleDbDataReader
        Dim command As New OleDbCommand("Insert into Donation (Donor_ID) VALUES ( " & txtDonNum.Text & "); Select @@Identity;")

        con.Open()
        command.Connection = con
        dr = command.ExecuteReader
        Dim Donation_ID As String = ""
        If dr.Read() Then
            Donation_ID = dr(0).ToString
            Dim food As New OleDbCommand("Insert into Food_Donation (Date_Received, Donation_ID) Val开发者_如何学运维ues ( '" & maskedreceived.Text & "', " & Donation_ID & "); Select @@Identity")
            food.Connection = con
            dr = food.ExecuteReader()
            'food.ExecuteNonQuery()
        End If
        Dim Food_ID As String
        If dr.Read() Then
            Food_ID = dr(0).ToString
            txtfoodid.Text = dr("Food_ID").ToString
        End If

    Catch ex As Exception

        MessageBox.Show(ex.Message)
    Finally
        con.Close()
    End Try

    MessageBox.Show("Food_ID has been made.")

End Sub

I've tried multiple ways of getting it to display but nothing's worked so far.


You are referencing column txtfoodid.Text = dr("Food_ID").ToString but your Select statement returns only @@Identity.

There is no Food_ID column returned from that reader. Either create a new Select query with it's own reader OR modify your second statement to return the Food_ID column.

Additionally your code here is incredibly susceptible to SQL injection types of attacks and would recommend reading Stop Sql Injection Attacks Before They Stop You


Pepto is mostly right. The only thing is, you have the information you need. Basically, just change this line

txtfoodid.Text = dr("Food_ID").ToString

to

txtfoodid.Text = Food_ID

and you will be good to go. You are trying to read the Food_ID out of the DataReader when you already got it and assigned it to the variable Food_ID.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜