+ 1

SqlDataAdapter Constructor

I'm trying to make a simple C# Windows Application to work with an existing sql database, which has a table named [dbo].[User] I want to create a search button, which searches for the user who has the name, which is written in the text box: txtName. My question is: Why do I have to pass a command to the SqlDataAdapter constructor? Why doesn't my code work when I pass a commandtext and a connection string? My program crashes and I receive the following error Message: System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@Name".' Here's part of my code: string SearchQuery = "select * from [dbo].[User] where [Name] = @Name"; using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); SqlCommand SearchCommand = new SqlCommand(SearchQuery, connection); SearchCommand.Parameters.AddWithValue("@Name", txtName.Text); //why does this work? SqlDataAdapter dataAdapter = new SqlDataAdapter(SearchCommand); //and not this: //SqlDataAdapter dataAdapter = new SqlDataAdapter(SearchQuery, connection); DataTable searched_users_Table = new DataTable(); dataAdapter.Fill(searched_users_Table); dgvUser.DataSource = searched_users_Table; connection.Close(); }

8th Jul 2023, 9:21 PM
H2727
H2727 - avatar
1 Resposta
+ 2
Check if this post helps you. https://stackoverflow.com/questions/8933634/must-declare-the-scalar-variable-username You should start debugging by determining which line of code causes the error. Usually this is printed in the error stack trace. Side note. I think your connection.Close() is redundant because the connection object is automatically disposed of, at the end of the 'using' block. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=dotnet-plat-ext-7.0 Generally it is a good idea to study the Microsoft documentation for the API that you are actually using. the text contains vital information about how to write your code in specific circumstances, and there are working examples you can adjust to your needs.
9th Jul 2023, 6:00 AM
Tibor Santa
Tibor Santa - avatar