I have code below which i use to select data from sql database table using dataadapter but i throws an error:
"Must declare the scalar variable"@UserName"
Where is the mistake in code????
I have tried the code below which throws an error "Must declare the scalar variable"@UserName"
Dim Query as string ="SELECT *FROM UserLogins WHERE [Login Name]=
@Username AND Password=@passcode"
// add parameters to dataadapter select command
SQL.da.SelectCommand.Parameters.AddWithValue("@Username", "%" +
txtuserName.Text + "%")
SQL.da.SelectCommand.Parameters.AddWithValue("@passcode", "%" +
txtpasslogin.Text + "%")
//execute query and fill dataset
da = New SqlDataAdapter(Query,Con)
cb = New SqlCommandBuilder(da)
ds = New DataSet
da.Fill(ds)
Datagridview1.Datasource=ds.tables(0)
Whew, ok, there's a lot of weird things going on with this code.
First. Two Slashes (//) is not how comments are done in VB.NET. That's C# syntax. Use the single quote instead (')
Next, the error you received is an error coming from SQL Server.
LarsTech specifically mentioned in his comment that the code you provided is adding the variables first and then creating a new instance of the SQLDataAdapter right after. If you modify your code to create the data adapter first, and then populate the variables, you should get a better result.
I'm not going to assume that the variables da, cb, and ds are already declared, but that the variable Con is declared somewhere.
Finally, your sql statement should also have a space between the * and the FROM, and as mentioned by Mary in comments, the % signs are not necessary here because you aren't doing a like.