首页 文章

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

提问于
浏览
0

I am able to display multiple selected items from a listbox into a text box on a button click but how can I display the same on a message box? I mean displaying first item on a messagebox is not an issue but multiple items at once is. Suggestions please...

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);
}

3 回答

  • 0

    您没有显示定义 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);
    }
    
  • 0

    您必须循环选定的项目并将其附加到文本框中 . 要在消息框上显示,您需要将所选项连接到字符串变量并将其用于您的消息 .

    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);
    
    }
    
  • 0

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

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

    如:

    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);
    }
    

相关问题