c# listbox使用

时间:2021-11-06 08:09:48

1.listbox在显示时很重要,尤其涉及到日志输出,串口输出,读取数据库的内容,结合定时器的使用,就更加好了。

2.所以写了一小例子,仅供参考,本篇也参考了别人写的代码,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace listbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string peopleText = textBox1.Text.Trim().ToString();
//获取listbox1的对象
ListBox list1 = this.listBox1;
//判断人员是否已经添加过
if (!list1.Items.Contains(peopleText))
{
//list1.Items.Add(peopleText);
list1.Items.Insert(0, peopleText);
}
else
{
MessageBox.Show("该人员已经添加过,无法重复添加!");
}
}

private void button2_Click(object sender, EventArgs e)
{
//获取listbox1的所有选中的项
if (this.listBox1.SelectedItems.Count > 0)
{
string checkPeople = this.listBox1.SelectedItem.ToString();
//判断是否添加到listbox2
if (!this.listBox2.Items.Contains(checkPeople))
{
//添加人员到listbox2中
this.listBox2.Items.Add(checkPeople);
//移除listbox1中
this.listBox1.Items.Remove(checkPeople);
}
else
{
MessageBox.Show("该人员已经转移过,无法重复转移!");
}

}
else
{
MessageBox.Show("未选中采购人员,,无法转移销售部门!");
}
}

private void button3_Click(object sender, EventArgs e)
{
//获取listbox2的所有选中的项
if (this.listBox2.SelectedItems.Count > 0)
{
string checkPeople = this.listBox2.SelectedItem.ToString();
//判断是否添加到listbox1
if (!this.listBox1.Items.Contains(checkPeople))
{
//添加人员到listbox1中
this.listBox1.Items.Add(checkPeople);
//移除listbox1中
this.listBox2.Items.Remove(checkPeople);
}
else
{
MessageBox.Show("该人员已经转移过,无法重复转移!");
}

}
else
{
MessageBox.Show("未选中销售人员,无法转移到采购部门!");
}
}
}
}