Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 在文本框中显示列表框中选择的数据时出现错误_.net_C# 4.0_Listbox - Fatal编程技术网

.net 在文本框中显示列表框中选择的数据时出现错误

.net 在文本框中显示列表框中选择的数据时出现错误,.net,c#-4.0,listbox,.net,C# 4.0,Listbox,我正在使用以下代码: private void listBox1_MouseClick(object sender, MouseEventArgs e) { txtFrom.Clear(); txtSubject.Clear(); txtBody.Clear(); something = this.listBox1.SelectedIndex.ToString(); int something1 = Convert.ToInt32(something);

我正在使用以下代码:

private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
    txtFrom.Clear();
    txtSubject.Clear();
    txtBody.Clear();
    something = this.listBox1.SelectedIndex.ToString();

    int something1 = Convert.ToInt32(something);

    foreach (MailMessage email in messages)
    {
        count++;
        if (count == something1)
        {
            txtFrom.Text = email.From.ToString();
            txtSubject.Text = email.Subject.ToString();
            txtBody.Text = email.Body.ToString();
        }
    }

问题是,当我选择另一项时,txtFrom.Text、txtSubject.Text、txtBody.Text的值不会根据列表框中选择的新值而改变。

如果您有兴趣在选择改变时学习,则
鼠标单击事件不是您想要处理的事件。无论用户是否进行选择,每次单击控件内部时都会引发
MouseClick
事件。有几种方法可以在列表框中选择项目,甚至不用鼠标。例如,我可以使用键盘上的箭头键更改选择。(如果这还不足以说服您,请注意,
MouseClick
事件“支持.NET Framework基础架构,不打算直接从您的代码中使用”。)

相反,您需要切换到处理事件。每次
SelectedIndex
属性(或多选列表框的
selectedDices
集合)更改时,都会引发该事件,每当进行/更改选择时都会自动发生

您甚至不必对代码进行任何其他更改:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    txtFrom.Clear();
    txtSubject.Clear();
    txtBody.Clear();
    something = this.listBox1.SelectedIndex.ToString();

    int something1 = Convert.ToInt32(something);

    foreach (MailMessage email in messages)
    {
        count++;
        if (count == something1)
        {
            txtFrom.Text = email.From.ToString();
            txtSubject.Text = email.Subject.ToString();
            txtBody.Text = email.Body.ToString();
        }
    }
}

当我运行listBox1_SelectedIndexChanged中的代码时,没有发生任何事情,因此我必须使用鼠标单击事件。@Iyrama25那么您没有正确连接事件处理程序。每次选择更改时都会引发此事件。这一点由文档保证。事实上,我链接到的文档甚至说:“当您需要根据列表框中的当前选择在其他控件中显示信息时,这可能很有用。您可以使用此事件的事件处理程序在其他控件中加载信息。”使用
鼠标单击
不是一个选项,因为它不起作用。你已经学到了很多。你需要弄清楚为什么
SelectedIndexChanged
没有被提升。这可能是因为,没有任何索引可供比较,它无法检测索引中的任何更改。我猜想,如果当前没有选择任何内容,则会选择某些内容,这仍然算作更改。价值从零到某物。