C# 转换nvarchar值时转换失败';System.Data.DataRowView';到数据类型int

C# 转换nvarchar值时转换失败';System.Data.DataRowView';到数据类型int,c#,sql-server,windows-applications,C#,Sql Server,Windows Applications,我正在尝试根据组合框选择填充DataGridView。我不知道我哪里出了问题,请帮忙 这是我的密码: public void GetTestGroups() { string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(CS)) { SqlDataAdapter da =

我正在尝试根据组合框选择填充
DataGridView
。我不知道我哪里出了问题,请帮忙

这是我的密码:

public void GetTestGroups()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlDataAdapter da = new SqlDataAdapter("select LabTestGroupId,GroupName from tbl_LabTestGroup", con);
        DataTable dt = new DataTable();
        da.Fill(dt);

        cbTestGroup.DataSource = dt;
        cbTestGroup.DisplayMember = "GroupName";
        cbTestGroup.ValueMember = "LabTestGroupId";           
    }
}

private void cbTestGroup_SelectedIndexChanged(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlDataAdapter da = new SqlDataAdapter("spGetTestNames", con);
        da.SelectCommand.CommandType = CommandType.StoredProcedure;

        da.SelectCommand.Parameters.AddWithValue("@LabTestGroupId", cbTestGroup.SelectedValue.ToString());

        DataTable dt = new DataTable();
        da.Fill(dt);// Error in this line.

        dgvLabTests.DataSource = dt;
    }
}
我的存储过程:

create procedure spGetTestNames 
    @LabTestGroupId int
as
begin 
    select TestNames 
    from tbl_LabTests 
    where LabTestGroupId = @LabTestGroupId
end

您正在向存储过程传递一个
字符串
,而存储过程需要一个
int
。如下更改设置
@LabTestGroupId
参数的代码

da.SelectCommand.Parameters.AddWithValue(
    "@LabTestGroupId", 
    int.Parse(cbTestGroup.SelectedValue.Item["LabTestGroupId"].ToString()));

或者,您需要确定如何将
SelectedValue
转换为所需的
int
值。我建议调试并查看watch窗口中的
SelectedValue
,以准确确定它是什么以及如何获得所需的值。

谢谢,但它不起作用。。它表示无法从对象转换为字符串。您可能需要执行
int.Parse(cbTestGroup.SelectedValue.ToString())
。尝试准确查看调试器中的
SelectedValue
是什么。我尝试过它说输入字符串的格式不正确
tbl_LabTests的数据类型是什么。LabTestGroupId
列那么
SelectedValue
应该是一个int,或者至少是一个可以转换为int的字符串。该列可以为null吗?如果是这样,
SelectedValue
是否可以用于
null
列?