错误是'从对象类型system.data.data.datarowview到已知的托管提供商本机类型。现在comBoxMuscleGroup.SelectedValue
和comBoxTypeFitness.SelectedValue
应该返回ID,而是返回'System.Data.DatarowView'。有人可以帮我吗?
代码:
private void TypeFitness()
{
string query = "SELECT Naam FROM TypeFitness";
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
DataTable data = new DataTable();
adapter.Fill(data);
comBoxTypeFitness.DisplayMember = "Naam";
comBoxTypeFitness.ValueMember = "FitnessId";
comBoxTypeFitness.DataSource = data;
}
}
private void MuscleGroup()
{
string query = "SELECT Naam FROM MuscleGroup";
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
DataTable data = new DataTable();
adapter.Fill(data);
comBoxMuscleGroup.DisplayMember = "Naam";
comBoxMuscleGroup.ValueMember = "MuscleId";
comBoxMuscleGroup.DataSource = data;
}
}
private void Exercises()
{
string query = "SELECT Naam FROM Xercises AS X " +
"INNER JOIN MG_Exercise AS MGX ON MGX.ExerciseId = X.ExerciseId " +
"WHERE MGX.MuscleId = @MuscleId AND X.FitnessId = @FitnessId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
//int MuscleId = ((DataRowView)comBoxMuscleGroup.SelectedValue).Row.Field<int>("MuscleId");
//int FitnessId = ((DataRowView)comBoxTypeFitness.SelectedValue).Row.Field<int>("FitnessId");
command.Parameters.AddWithValue("@MuscleId", comBoxMuscleGroup.SelectedValue);
command.Parameters.AddWithValue("@FitnessId", comBoxTypeFitness.SelectedValue);
DataTable data = new DataTable();
adapter.Fill(data);
clbXcercises.DisplayMember = "Naam";
clbXcercises.ValueMember = "ExerciseId";
clbXcercises.DataSource = data;
}
}
属性valuemember和displaymember是两个字符串,应该是两个字段的名称,可提供来自数据源的值。
您的查询不包含您为组合的命名为ValueMember的字段。
因此,它不可能在属性中给出精确的值,而只是用于在组合内构建一行的类的名称(dataRowView)
如果要将所选值设置为当前选定项目的MuscleID或FitnessID值,则需要从数据库中提取这些值。
您需要将查询更改为
string query = "SELECT FitnessID, Naam FROM TypeFitness";
和
string query = "SELECT MuscleID, Naam FROM MuscleGroup";
最终查询还需要进行练习
string query = "SELECT ExerciseID, Naam FROM Xercises AS X " +
"INNER JOIN MG_Exercise AS MGX ON MGX.ExerciseId = X.ExerciseId " +
"WHERE MGX.MuscleId = @MuscleId AND X.FitnessId = @FitnessId";
我还建议在使用之前始终检查针对所选价值属性的空。