我想从数据库中获取数据并根据用户在列表视图中选择的内容显示在标签中。
我要给出一个使用两个列表视图执行此操作的示例,但是当我向标签发送数据时我不知道该怎么做。
这是我正在使用的列表视图示例(我的标签代码在此下方)
private void PopulateRecipeIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = @RecipeId";
// @ is a parameter
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
// whatever recipe is selected in lstRecipes box, get the id of that and pass into query above
command.Parameters.AddWithValue("@RecipeId", lstRecipes.SelectedValue);
// DataTable holds the data return from query
DataTable ingredientTable = new DataTable();
// SqlDataAdapter object adapter fills the ingredientTable DataTable object with results from query
adapter.Fill(ingredientTable);
// Display value of Name ex. salad
lstIngredients.DisplayMember = "Name";
// Id column is how we reference
lstIngredients.ValueMember = "Id";
// connect list box on form to data in recipeTable
lstIngredients.DataSource = ingredientTable;
}
}
我的代码:
private void PopulateCourseDetails()
{
string query = "SELECT * FROM Course_Info WHERE Id = @CourseId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("@CourseId", lstCourses.SelectedValue);
DataTable courseTable = new DataTable();
adapter.Fill(courseTable);
lblCourseId.Text = "Course_id";
lblCourseSection.Text = "Course_section";
lblCourseName.Text = "Course_name";
lblCourseDay.Text = "Course_day";
lblCourseStartTime.Text = "Course_start_time";
lblCourseEndTime.Text = "Course_end_time";
lblCourseProfessor.Text = "Course_professor";
lblCourseProfessorEmail.Text = "Course_professor_email";
lstCourses.ValueMember = "Id";
}
}
答案 0 :(得分:0)
lblCourseId.Text = (string)courseTable.Rows[0]["Course_id"]
只要结果表中有一行,就应该起作用
答案 1 :(得分:0)
假设您的DataTable现在已正确填充,那么您现在有了一个包含许多行的表。
首先,您需要拉出第一行
var row = courseTable.Rows.FirstOrDefault();
现在,您已经有了一行包含许多列的行。您可以按索引或列名访问每一列。
lblCourseId.Text = row[0];
如果您希望标签保留其标题,可以执行
lblCourseId.Text = "Course_id: " + row[0];