如何在where子句中使用ComboBox SelectedValue

时间:2015-10-02 11:36:48

标签: c# winforms combobox where-in

我尝试使用此代码,但在where子句中出现错误。

var subComTbl = from subCom in myDb.SubComTbls
where subCom.AuthorityID.ToString()== Authoritycombo.SelectedValue
select subCom;
SubComcombo.Visible = true;
SubComcombo.DataSource = subComTbl;
SubComcombo.DisplayMember = "SubComName";
SubComcombo.ValueMember = "SubComID";

2 个答案:

答案 0 :(得分:1)

看来你应该注意编译器警告。

  

可能的意外参考比较;得到一个价值比较,   施放右侧以输入'string'

SelectedValue属性属于object类型。您应该使用Authoritycombo.SelectedValue.ToString()

where subCom.AuthorityID.ToString()== Authoritycombo.SelectedValue.ToString()

==的两个操作数应该是相同的类型,因此如果您在左侧使用subCom.AuthorityID,则右侧的另一个操作数应与AuthorityID的类型相同或者你在左边使用Authoritycombo.SelectedValue.ToString(),右边的另一个操作数应该是字符串的类型。

答案 1 :(得分:0)

您不需要将SelectedValuesubCom.AuthorityID转换为字符串来表示这些值。

SelectedValue包含与DataSource的属性(或列)类型相同的类型值

在您的情况下,我认为AuthorityIDSubComID属性是整数
因此,您只需在比较

之前在SelectedValue中检查空值
SubComcombo.Visible = true;
SubComcombo.DataSource = subComTbl;
SubComcombo.DisplayMember = "SubComName";
SubComcombo.ValueMember = "SubComID";

Int32 selectedID = -1; //default value which for sure not in the database
if(Authoritycombo.SelectedValue != null)
    selectedID = (Int32)Authoritycombo.SelectedValue;

var subComTbl = from subCom in myDb.SubComTbls
                where subCom.AuthorityID == selectedID 
                select subCom;