1

我将 ArrayList() 绑定到 Listbox 控件,并为数组中的数据分配 Displaymember 和 Value。我的问题是我在启动时绑定但在几次函数调用后数组被填满。我在 selectedIndexChanged 上有代码来检查 selectedValue,但是如果 ArrayList 为空,它会返回一个对象,一旦它有数据,它就会返回我期望的字符串。我仍然很困惑为什么当列表没有数据时它会运行 selectedIndexChanged 。认为它可能会在我绑定 Displaymember 之后但在分配值之前运行:

lbCAT_USER.DataSource = USERS;
// Running here maybe?
lbCAT_USER.DisplayMember = "DisplayString";
// Or Here?
lbCAT_USER.ValueMember = "ID";

无论哪种方式,我当前的工作都是尝试/捕获将 SelectedValue 与字符串进行比较并尝试重新运行该函数。

简单的解决方法可能是在 if 语句之前检查数据类型的一种方法?任何建议的想法都可能非常有帮助。谢谢

4

5 回答 5

10

您有两种方法可以检查:

string value = list.SelectedValue as string;

// The cast will return null if selectedvalue was not a string.
if( value == null ) return; 

//Logic goes here.

如果您只想进行比较:

if( list.SelectedValue is string )
{
   // ...
}
于 2009-07-22T15:19:29.537 回答
1

如果您的问题是如何通过 if-condition(标题!)检查值的数据类型,那么就可以了(例如:检查值是否为“字符串”类型):

if(value.GetType().Equals(typeof(string)))
{
   ...
}

编辑:这不是最干净的方法。查看 Guard 的答案以获取更复杂的检查类型的方法。像我一样使用“GetType().Equals”比“is”或“as”更精确,因为“value”必须完全属于“string”类型。即使 'value' 是检查类型的子类,'is' 和 'as' 也会起作用。尽管与“字符串”类型进行比较时,这无关紧要,因为您不能从字符串继承。

于 2009-07-22T15:15:18.293 回答
0

处理值为空的情况:

if (typeof(value) == typeof(string))
{
    ...
}
于 2009-07-22T15:20:30.983 回答
0

我相信你也可以使用:

if (value is string)
{
}

在 C# 中检查变量的类型。

于 2009-07-22T15:21:32.607 回答
0

是的,他们都调用 OnSelectedIndexChanged() 事件

you can check this by placing break points on the the OnSelectedIndexChanged handler and stepping through.

You could un-hook the OnSelectedIndexChanged event when you do the data binding

this.ListBox.SelectedIndexChanged -= OnSelectedIndexChangedHandler;

this.ListBox.DataSource = dataSource;
this.ListBox.ValueMember = "ID"
this.ListBox.DisplayMember = "Name"

this.ListBox.SelectedIndexChanged += OnSelectedIndexChangedHandler;

Or just check the value like others have suggested on the OnSelectedIndexChanged event.

Doing both can't hurt

于 2009-07-22T15:33:59.217 回答