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 回答
您没有显示定义
Skill
的位置,但可能是该类的属性 . 您只在checkedListBox1_ItemCheck
中初始化Skill
. 如果选择已更改,则该值将过时(它不会反映现实) .对代码的最短更改是在按钮处理程序中不使用
Skill
,而是从列表框中获取当前状态(如果您喜欢该样式,可能将其放在局部变量中) .您必须循环选定的项目并将其附加到文本框中 . 要在消息框上显示,您需要将所选项连接到字符串变量并将其用于您的消息 .
看起来你用要检查的最后一个值覆盖
Skill
. 因此,我希望消息框始终显示与您单击的最后一项相关的Skill
. 所以,如果你想显示所有这些,你需要在MessageBox.Show
调用中用listBox1.Items.Cast<string>().Aggregate((o, n) => o.ToString() + "," + n.ToString())
替换Skill
*注意:将
Cast<string>
替换为任何类型的对象Skill
.如: