Combobox 和 SelectionChanged 问题
我正在尝试检查组合框中的值,但它失败了,我的值从未匹配,并且我收到此警告:
可能的意外引用 比较;进行价值比较, 投射左侧进行打字 '字符串'
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ComboBox)sender).SelectedValue == "Floyd-Warshall")
{
MessageBox.Show("foobar");
谢谢。
I'm trying to check for a value in my combobox, but it fails, my value is never matched and I have this warning :
Possible unintended reference
comparison; to get a value comparison,
cast the left hand side to type
'string'
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ComboBox)sender).SelectedValue == "Floyd-Warshall")
{
MessageBox.Show("foobar");
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有多种修复方法,一种是转换为字符串,另一种是对 SelectedValue 调用 ToString。
正如您所说,其他一些建议的答案不起作用,您确定组合框中的项目实际上是一个字符串吗?
例如,这将适用于建议的修复:
但这不会:
您可以通过在现有事件处理程序中运行以下代码来快速确定是否是这种情况:
There are various ways to fix, one if to cast to a string, the other is to call ToString on the SelectedValue.
As you have stated that some of the other suggested answers do not work, are you sure the item in the Combobox is in fact a string?
For example, this will work with the fixes suggested:
But this won't:
You can quickly determine if this is the case by running the following code in your existing event handler:
SelectedValue 的类型是
object
因此,即使它与值匹配,相等操作也会返回 false,因此您必须将字符串与字符串进行比较,如下所示:SelectedValue's type is
object
so, even it matches the value the equal operation will return false, so you have to compare string with string instead like the following:SelectedValue 的警告,您必须添加 .toString()
the warning for the SelectedValue you have to add .toString()