从调用方法获得RETURN

| 我试图从另一个线程上的列表框项目中读取值。 我试图制作一个新方法来运行invoke命令,我可以通过invoke方法将命令添加到列表框中,例如add,但是我似乎无法获得响应,我似乎无法获得该项目的价值,尝试了几种方法,一旦我将其从空变为字符串,事情就会开始变得多毛...
  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<String>(() => readListBoxSelected(listbox))
            );
        }
        else
        {

            string varText = listbox.SelectedValue.ToString();
            return varText;
        }
        }
以上是我正在尝试做的一个例子。 这是错误:   System.NullReferenceException原为   用户代码未处理   Message =对象引用未设置为   对象的实例。   来源= ** StackTrace:          在**。Form1.readListBoxSelected(ListBox listbox)在e:\\ documents和   设置\\斯科特\\我的文档\\视觉   工作室   2010 \\ Projects ***** \\ Form1.cs:line   133          在***。Form1。<> c_DisplayClass5.b_3()   在e:\\ documents and settings \\ scott \\ my   文件\\视觉工作室   2010 \\ Projects ****** \\ Form1.cs:line   127 InnerException: 我想我想错了什么,就是“对象引用未设置为对象的实例”。............据我所知,我所有的变量似乎都被声明为公平的,我该如何纠正呢? ?? 我感觉到我错了整个事情。...0_o 提前致谢, 史考特     
已邀请:
        尝试这个
public static string readListBoxSelected(ListBox listbox)
    {
        if (listbox.InvokeRequired)
        {
            return (string)listbox.Invoke(
              new Func<String>(() => 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没什么,它没有做我们大家都想象的那样...我需要的呼叫是listbox.Text .........
public static string readListBoxSelected(ListBox listbox)
{
    if (listbox.InvokeRequired)
    {
        return (string)listbox.Invoke(
          new Func<String>(() => 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确实不是在读取selectvalue之后的调用im(您会认为是),如果我将其更改为listbox1.text则一切正常。如果我确实这么说的话.... 我必须说个笑话……这真是破坏了我对面向对象编程的信念。 我知道这不是讨论的话题,但是说实话,调用SelectedValue.toString()应该做我们都认为会做的事情....不,我们需要使用.Text来获取我们需要的0_o ....... ..     

要回复问题请先登录注册