【问题标题】:Can't add strings to listbox无法将字符串添加到列表框
【发布时间】:2015-05-13 23:42:59
【问题描述】:

您好,我正在尝试将 this 库的输出收集到列表框中。

这是来自测试项目的部分代码,我已尝试修改:

public partial class Form1 : Form
{
    D.Net.Clipboard.ClipboardManager Manager;

    public Form1()
    {
        InitializeComponent();
        Manager = new D.Net.Clipboard.ClipboardManager(this);
        Manager.Type = D.Net.Clipboard.ClipboardManager.CheckType.Text;
        Manager.OnNewTextFound += (sender, eventArg) =>
        {
            button1.Text = eventArg;            //just testing, working correctly
            listBox1.Items.Add(eventArg);       //does not show neither result nor any error
            MessageBox.Show(String.Format("New text found in clipboard : {0}", eventArg));
        };
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add("test");             //working correctly
    }
}

问题是当我尝试将项目添加到列表中时它什么也不做,并且进一步的代码行(在此函数中)根本不运行。

我尝试通过一些自定义类和不同的表达式来修复它,但对我没有任何帮助(是的,我是菜鸟)。也尝试用 textBox 来做,结果是一样的,但是按钮上的文本会改变。

看起来完全是蹩脚的问题,但我已经花了将近 5 个小时通过谷歌搜索、阅读微软文档、SO,我能得到的最接近的是 this,因为我可以看到那里建议的东西已经实现。

【问题讨论】:

  • 尝试使用listBox1.Items.Add(eventArg.ToString()); 看看是否可行。
  • button1.Text = eventArg; 甚至不会为我编译。
  • @Grant Winney 是的,工作应该@dub stylee,不,它没有

标签: c# winforms listbox


【解决方案1】:

OnNewTextFound 事件在与 UI 不同的线程上触发,因此您更新 UI 的尝试失败。另一个线程中抛出异常,中止该方法的其余部分,但您的 UI 线程继续执行。

您必须调用 Invoke() 才能在 UI 线程上执行代码:

listBox1.Invoke(new MethodInvoker(delegate { listBox1.Items.Add(eventArg); }));

【讨论】:

    【解决方案2】:

    您正在将 EventArgs 添加到 ListBox 的 Items 列表中。有没有可以添加的 eventArgs.[someString]?

    【讨论】:

    • 不,VS 建议只是标准操作,在库代码中没有公布,但我可以看到 string text
    • 我现在明白了。委托使用第二个参数声明为字符串。我的下一个问题是事件何时被触发? eventArg 可以为空吗?也许添加一个空检查以仅添加具有值的项目。 IE。 If (!string.IsNullOrEmpty(eventArg)) { listBox1.Items.Add(eventArg); }
    【解决方案3】:

    在表单的构建过程中,您不能将项目添加到列表框。您需要将代码移动到 Load 事件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2017-10-09
      • 2011-09-10
      • 2018-08-12
      • 2014-07-05
      • 2013-12-23
      相关资源
      最近更新 更多