C# delete the selected item in the ListBox, add

//button3_Click是删除按钮
//listBox1是列表框
 private void button3_Click(object sender, EventArgs e)
        {
    
    
        //由于列表框控件中允许多选所以需要循环删除所有已选项
            int count = listBox1.SelectedItems.Count;//判断选中了几个
            List<string> itemValues = new List<string>();
           
            if (count == 0)
            {
    
    
            //如果所选项个数为0,则进行提示
                MessageBox.Show("请选择需要删除的内容!");
            }
            else
            {
    
    
           		//将选中项的内容添加到字符串列表中
                for (int i = 0; i < count; i++)
                {
    
    
                   itemValues.Add(listBox1.SelectedItems[i].ToString());
                }
                //按照内容从列表框中移除数据
                foreach (string item in itemValues)
                {
    
    
                    listBox1.Items.Remove(item);
                }
                MessageBox.Show("删除成功!");
            }

        }
//将文本框中的值添加到列表框中
//button2_Click是添加按钮
private void button2_Click(object sender, EventArgs e)
{
    
    
    //当文本框中的值不为空时将其添加到列表框中
    if (textBox1.Text != "")
    {
    
    
        listBox1.Items.Add(textBox1.Text);
    }
    else
    {
    
    
        MessageBox.Show("请添加爱好!");
    }
}
//button1_Click 展示
//用提示框显示选中的所有项内容
        private void button1_Click(object sender, EventArgs e)
        {
    
    
            string msg = "";
           // listBox1.SelectedItems.Count 选中项的总个数
            for (int i=0;i<listBox1.SelectedItems.Count;i++)
            {
    
    
            //listBox1.SelectedItems[i].ToString()选中项的值
                msg = " " + msg + listBox1.SelectedItems[i].ToString();

            }
            if (msg != "")
            {
    
    
                MessageBox.Show("您选择的水果是:" + msg, "提示");
            }
            else
            {
    
    
                MessageBox.Show("您没有选择水果", "提示");
            }
        }

Guess you like

Origin blog.csdn.net/weixin_49035356/article/details/112779531