C# 如何在where子句中使用ComboBox SelectedValue
我尝试了这段代码,但在C# 如何在where子句中使用ComboBox SelectedValue,c#,winforms,combobox,where-in,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 = "S
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";
似乎您应该注意编译器警告 可能的非预期参考比较;要进行价值比较, 将右侧强制转换为键入“string”
SelectedValue
属性属于对象类型。您应该使用Authoritycombo.SelectedValue.ToString()
==
的两个操作数应为同一类型,因此如果您在左侧使用subCom.AuthorityID
,则右侧的另一个操作数应与AuthorityID
的类型相同,或者如果您使用Authoritycombo.SelectedValue.ToString()
左侧的另一个操作数应为字符串类型。您不需要将SelectedValue
和subCom.AuthorityID
转换为字符串来共享这些值
SelectedValue
包含与数据源的属性(或列)类型相同类型的值
在您的情况下,我假设AuthorityID
和subcompid
属性是整数因此,在比较之前,您只需在
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;
Authoritycombo或subCom.AuthorityID为Null请告诉我它是否解决了问题。@MUAl-t是的,请使用==
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;