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(); }