【问题标题】:How to use ComboBox SelectedValue in where clause如何在 where 子句中使用 ComboBox SelectedValue
【发布时间】:2015-10-02 11:36:47
【问题描述】:

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

【问题讨论】:

  • Authoritycombo 或 subCom.AuthorityID 为空
  • 如果它解决了问题,请告诉我。

标签: c# winforms combobox where-in


【解决方案1】:

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

可能的意外参考比较;进行价值比较, 将右侧强制转换为“字符串”

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

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

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

【讨论】:

  • @MUAl-t 是的,用 == 这样做
【解决方案2】:

您不需要将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;

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2020-11-30
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多