如何在where子句中使用ComboBox SelectedValue

本文关键字:ComboBox SelectedValue 子句 where | 更新日期: 2023-09-27 18:15:35

我尝试了这个代码,但在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";

如何在where子句中使用ComboBox SelectedValue

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

可能存在非预期的引用比较;为了得到一个值比较,将右侧强制转换为键入'string'

SelectedValue属性属于对象类型。你应该使用Authoritycombo.SelectedValue.ToString()

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

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

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

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

在您的情况下,我假设AuthorityIDSubComID属性是整数
因此,在比较

之前,您只需要检查SelectedValue中的null。
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;