我正在尝试创建一个食谱数据库,该数据库从用户那里获取配料并输出包含所述配料的食谱。我试图用 sql 语句的结果填充数据 GridView ,但在我的网格中没有得到任何结果。我的 SQL 语句是正确的。这是我的代码:
结果窗口:
private void resultsWindow_Load(object sender, EventArgs e)
{
//get connection string
string connectionString = Properties.Settings.Default.ConnectionString;
DataSet recipeDataSet = new DataSet();
conn = new DatabaseConnections(connectionString);
//Get dataset
recipeDataSet = conn.getRecipes(ingredientArray);
//Display data in grid view
recipesDataGrid.DataSource = recipeDataSet.Tables[0];
}
数据库连接窗口:
public DataSet getRecipes(string[] ingArray)
{
string sqlString = "SELECT recipes.Name, Instructions, recipes.Preperation_Time, Author FROM RecipeIngredients" +
" INNER JOIN recipes ON recipes.Recipe_ID = RecipeIngredients.Recipe_ID" +
" INNER JOIN Ingredients ON Ingredients.Ingredient_ID = RecipeIngredients.Ingredient_ID" +
" WHERE ingredients.Name = 'Eggs'";
DataSet recipeDataSet = new DataSet();
DataTable recipeDataTable = new DataTable();
openConnection();
dataAdapter = new SqlDataAdapter(sqlString, connectionToDB);
//Fill dataset
dataAdapter.Fill(recipeDataTable);
recipeDataSet.Tables.Add(recipeDataTable);
dataAdapter.Fill(recipeDataSet);
closeConnection();
return recipeDataSet;
}
This is the data grid once I run the program
提前致谢。
编辑: 我意识到不是我的数据表/数据集不起作用,而是我的 SQL 语句似乎没有返回任何内容,即使当我将它作为一个单独的查询时我得到了结果。
最佳答案
试试吧..我不确定
private void resultsWindow_Load(object sender, EventArgs e)
{
//gets connection string
string connectionString = Properties.Settings.Default.ConnectionString;
DataSet recipeDataSet = new DataSet();
conn = new DatabaseConnections(connectionString);
//Gets dataset
Datatable dt1 = conn.getRecipes(ingredientArray);
//Displays data in grid view
recipesDataGrid.DataSource = dt1.DefaultView;
}
public DataTable getRecipes(string[] ingArray)
{
string sqlString = "SELECT recipes.Name, Instructions, recipes.Preperation_Time, Author FROM RecipeIngredients" +
" INNER JOIN recipes ON recipes.Recipe_ID = RecipeIngredients.Recipe_ID" +
" INNER JOIN Ingredients ON Ingredients.Ingredient_ID = RecipeIngredients.Ingredient_ID" +
" WHERE ingredients.Name = 'Eggs'";
DataTable recipeDataTable = new DataTable();
openConnection();
dataAdapter = new SqlDataAdapter(sqlString, connectionToDB);
//Fills dataset
dataAdapter.Fill(recipeDataTable);
closeConnection();
return recipeDataTable;
关于c# - 使用数据集填充 dataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55309873/