繁体   English   中英

在C#Windows窗体的消息框中显示列表框的选定项目

[英]Displaying selected items of listbox into a message box in C# Windows Form

我可以在单击按钮时将列表框中的多个选定项目显示到文本框中,但是如何在消息框中显示相同的内容? 我的意思是在消息框中显示第一个项目不是问题,但一次有多个项目是一个问题。 建议...

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{

    Skill = checkedListBox1.SelectedItem.ToString();
    if (e.NewValue == CheckState.Checked)
    {
        listBox1.Items.Add(Skill);
    }
    else
    {
        listBox1.Items.Remove(Skill);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("You have selected following Skills : \n"+Skill, "Selected Skills",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
}

您不会显示Skill的定义位置,而应该显示为类的一个属性。 您只能在checkedListBox1_ItemCheck初始化Skill 如果选择已更改,则该值将是陈旧的(不会反映现实)。

对代码的最短更改是不在按钮处理程序中使用Skill ,而是从列表框中获取当前状态(如果您喜欢该样式,则可以将其置于局部变量中)。

private void button1_Click(object sender, EventArgs e)
{
    var selectedSkills = checkedListBox1.SelectedItem.ToString();
    MessageBox.Show("You have selected following Skills : \n"+selectedSkills, "Selected Skills",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
}

看来您正在用要检查的最后一个值覆盖Skill 因此,我希望消息框始终显示与您单击的最后一项相关的Skill 因此,如果要显示所有这些内容,则需要使用诸如listBox1.Items.Cast<string>().Aggregate((o, n) => o.ToString() + "," + n.ToString())东西替换MessageBox.Show调用中的Skill listBox1.Items.Cast<string>().Aggregate((o, n) => o.ToString() + "," + n.ToString())

*注意:用任何类型的对象Skill替换Cast<string>

如:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    Skill = checkedListBox1.SelectedItem.ToString();

    if (e.NewValue == CheckState.Checked)
    {
        listBox1.Items.Add(Skill);
    }
    else
    {
        listBox1.Items.Remove(Skill);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("You have selected following Skills : \n"+ listBox1.Items.Cast<string>().Aggregate((o, n) => o.ToString() + "," + n.ToString()), "Selected Skills",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
}

您必须遍历所选项目并将其附加到文本框中。 为了在消息框上显示,您需要将所选项目连接到字符串变量,并将其用于消息。

private void button1_Click(object sender, EventArgs e)
{
    StringBuilder skills = new StringBuilder();
    foreach (object item in listBox1.SelectedItems)
    {
        skills.AppendLine(item.ToString());
    }

    MessageBox.Show("You have selected following Skills : \n" + skills.ToString(), "Selected Skills",
    MessageBoxButtons.OK, MessageBoxIcon.Information);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM