Reputation: 41
I am trying to learn to work with database on visual studio. I have copied the following code from a guy on YouTube with no errors, but i still get an error.
I have a problem with the following code:
public partial class FormMain : Form
{
SqlConnection connection;
string ConnectionString;
public FormMain()
{
InitializeComponent();
ConnectionString = ConfigurationManager.ConnectionStrings["denis_project.Properties.Settings.denisdatabaseConnectionString"].ConnectionString;
}
private void FormMain_Load(object sender, EventArgs e)
{
PopulateRecipes();
}
private void PopulateRecipes()
{
using (connection = new SqlConnection(ConnectionString))
using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Recipe", connection))
{
DataTable recipeTable = new DataTable();
adapter.Fill(recipeTable);
lstRecipes.DisplayMember = "Name";
lstRecipes.ValueMember = "Id";
lstRecipes.DataSource = recipeTable;
}
}
private void PopulateIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId" +
"WHERE b.RecipeId = @RecipeId";
using (connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("@RecipeId", lstRecipes.SelectedValue);
DataTable ingredientTable = new DataTable();
adapter.Fill(ingredientTable);
lstIngredients.DisplayMember = "Name";
lstIngredients.ValueMember = "Id";
lstIngredients.DataSource = ingredientTable;
}
}
private void lstRecipes_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateIngredients();
}
}
The problem is this code throws an error on this line:
adapter.Fill(ingredientTable);
The error says:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'b'.'
I tried to look for any error in my code but I have not found any kind of error.
Maybe that can help, I copied it from SQLQuery1.sql
:
SELECT * FROM recipe
SELECT * FROM Ingredient
SELECT a.Name
FROM Ingredient a
INNER JOIN RecipeIngredient b ON a.Id = b.Ingredientid
Upvotes: 2
Views: 60
Reputation: 112
May be you should add a space before WHERE clause:
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId" +
" WHERE b.RecipeId = @RecipeId";
Upvotes: 1