从Invoke方法获取RETURN

我试图从另一个线程上的列表框项读取值。

我试图创建一个新的方法来运行invoke命令,我可以设法发送命令到列表框,如通过调用方法添加,但我似乎无法得到响应,我似乎无法得到项目的价值,我尝试了几种方法,一旦我将它从一个空格改为一个字符串,事情开始变得毛茸茸……

thread t1 = new thread(thethread) t1.start() public void thethread() { string text = readListBoxSelected(listBox1) + " lala" ; } public static string readListBoxSelected(ListBox listbox) { if (listbox.InvokeRequired) { return (string)listbox.Invoke( new Func(() => readListBoxSelected(listbox)) ); } else { string varText = listbox.SelectedValue.ToString(); return varText; } } 

以上是我想要做的一个例子。

这是错误:

System.NullReferenceException未被用户代码处理
Message =对象引用未设置为对象的实例。
Source = * * StackTrace:at * * .Form1.readListBoxSelected(ListBox listbox)在e:\ documents and settings \ scott \ my documents \ visual studio 2010 \ Projects ** * * * \ Form1.cs:第133行** * .Form1。 c_ DisplayClass5.b _3()在e:\ documents和settings \ scott \ my documents \ visual studio 2010 \ Projects ** * * ** \ Form1.cs:line 127 InnerException:

我想错的正是它所说的“对象引用没有设置为对象的实例”…….所有我的变量似乎被宣布为公平,因为我知道,我怎么能纠正这个?

我感觉我错误地处理了整个事情…… 0_o先谢谢你,斯科特

试试这个

 public static string readListBoxSelected(ListBox listbox) { if (listbox.InvokeRequired) { return (string)listbox.Invoke( new Func(() => readListBoxSelected(listbox)) ); } else { if(istbox.SelectedValue != null) return listbox.SelectedValue.ToString(); else return String.Empty } } 

代码看起来很好,问题似乎在SelectedValue上 ,是否为null 。 ???

多谢你们,

你在哪里正确,问题是它返回一个空值..我很确定我正确选择项目我从未想过它可能是问题。

原来问题是两件事:

1)我选择项目的方式,我使用listbox.Selecteditem = 1,现在如果我使用listbox.setSelected(1,true)一切都很好:)

2)我获取项目文本的方式是错误的,listbox.SelectedValue是什么,它dosnt做我们都想象它做…我需要的调用是listbox.Text ………

 public static string readListBoxSelected(ListBox listbox) { if (listbox.InvokeRequired) { return (string)listbox.Invoke( new Func(() => readListBoxSelected(listbox)) ); } else if(listbox.Text != null) { return listbox.Text.ToString(); } else return String.Empty; } public void selectListBoxItem(ListBox listbox, int num) { Invoke(new MethodInvoker(delegate { listbox.SetSelected(num,true); })); } 

我必须说这是我做过的最令人讨厌的事情……一切都要求我为它写一个委托/调用方法……一切……如此普遍的东西会被.net在飞行中支持….

似乎只有一段时间来为个人代表写一切……

谢谢大家现在都在工作,昨天我无法预见到这一点, 总体问题是错误的电话,调用都很好:)

斯科特

编辑:

确定它返回NULL只是因为listbox.SelectedValue不是真正的调用im后读取selectedvalue(你会认为它是),如果我将它更改为listbox1.text一切正常….相当愚蠢这个.net面向对象如果我这样说的东西….

我必须说出一个笑话……那善意破坏了我对面向对象编程的信念。我明白这不是讨论四,但老实说调用SelectedValue.toString()应该做我们都认为会做的事情….不,我们需要使用.Text来得到我们需要的东西0_o ………