c# winform上下车练习题
电脑版发表于:2020/10/13 16:21
效果如下:其实就是一个很简单的集合练习题
输入可以上车,选择可以下车,点击显示可以看到所有的乘客。代码如下:
public partial class Form1 : Form { List<string> passagerList = new List<string>(); public Form1() { InitializeComponent(); //绑定事件 load_button.Click += load_button_Click; } /// <summary> /// 获取现有的所有乘客信息 /// </summary> /// <returns></returns> public string GetAllPassager() { string passagers = ""; foreach (string item in passagerList) { passagers += item + ","; } //去掉最后一个逗号 //passagers = passagers.Substring(0, passagers.Length - 1);//方法1:截取字符串 passagers = passagers.TrimEnd(','); return passagers; } void load_button_Click(object sender, EventArgs e) { string passger = pa_textBox.Text; //上车之前验证一下乘客是否存在 if (passagerList.Contains(passger)) { MessageBox.Show("乘客已经存在"); return; } passagerList.Add(passger); //show_label.Text += ","+ passger ; //show_label.Text = show_label.Text.TrimEnd(','); show_label.Text = GetAllPassager(); pa_textBox.Text = ""; //把乘客显示在列表里边 pas_comboBox.Items.Add(passger); pas_comboBox.SelectedIndex = 0; //把乘客信息显示到label上面 //foreach (string item in passagerList) //{ // show_label.Text += passger + ","; //} } private void show_linklabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { string passagers = GetAllPassager(); MessageBox.Show(passagers); } /// <summary> /// 下车 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void offload_button_Click(object sender, EventArgs e) { //获取到选择的用户 // string passager = pas_comboBox.SelectedValue.ToString(); string passager = pas_comboBox.SelectedItem + ""; passagerList.Remove(passager); //从下拉列表中删除 pas_comboBox.Items.Remove(passager); pas_comboBox.Text = ""; //下次的时候也要去动态修改一下显示的label string passagers = GetAllPassager(); show_label.Text = passagers; } }