Reputation: 444
Sorry if this question is stupid but I have no other way to see the big picture. I have 1 textbox, 1 label and database with two columns (codename and description), by entering codename in textbox I would like to get corresponding description in label.
With Excel and VBA it can be done with couple of lines. Sadly I can not use Excel but have to choose Web interface 'cause of slow PCs and Office price. Why is this simple task so complicated in ASP.NET with all general declarations and sqlservers and sqlconnections.
Is there a simpler way to do this?
BTW. I've tried to adapt many different things I've found on the web and this last one looks promising but it doesn't work :
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True"), _
sqlcmd As New SqlCommand("Select From Baza Where SIFRE = @SIFRE", sqlconn)
sqlcmd.Parameters.Add("@SIFRE", SqlDbType.VarChar, 50).Value = TextBox2.Text
sqlconn.Open()
'Label1.Text = CString(sqlcmd.ExecuteScalar()) 'CString is not declared
Label1.Text = sqlcmd.ExecuteScalar()
End Using
End Sub
Where Baza is Table name,
SIFRE is codename that will be entered in textbox
and NAZIV is description corresponding to SIFRE and should be shown in Label
Upvotes: 4
Views: 126
Reputation: 216302
The correct form is
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True")
Using sqlcmd = New SqlCommand("Select NAZIV From Baza Where SIFRE = @SIFRE", sqlconn)
sqlcmd.Parameters.AddWithValue("@SIFRE", TextBox2.Text)
sqlconn.Open()
Dim result = sqlcmd.ExecuteScalar()
if result IsNot Nothing Then
Label1.Text = result.ToString
End If
End Using
End Using
End Sub
The SELECT sql clause is followed by the list of columns you want to retrieve. (Added NAZIV)
Also you should consider that your query could not find a value for the parameter @Sifre and, in that case, the result of the ExecuteScalar is Nothing.
Upvotes: 4