C#编程,使用泛型集合添加职员信息:
程序运行界面:
程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class ListAdd : Form
{
public ListAdd()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//定义泛型集合
List<string> list_staff = new List<string>();
string staffs = "";
//定义字符串数组
string[] arr_staff, arr_staffinfo;
//泛型集合赋值
list_staff.Add("李明 男 23 销售部");
list_staff.Add("王雷 女 28 营销部");
list_staff.Add("赵凤 男 24 公关部");
list_staff.Add("张牛 男 26 人事部");
list_staff.Add("杨马 女 22 宣传部");
//使用分号将集合中的每一个字符串进行分开
foreach (string str in list_staff)
{
staffs += str + ";";
}
//通过识别分号,来拆分集合中的字符串,并存储到字符串数组中
arr_staffinfo = staffs.Split(';');
//为数据表添加5行
dataGridView1.Rows.Add(5);
//将每一个字符串中的每个元素进行分开并显示到数据表中
for (int i = 0; i < arr_staffinfo.Length - 1; i++) //注意Length-1
{
//用空格将每一行字符串中的元素进行分开
arr_staff = arr_staffinfo[i].Split(' ');
//将每个元素显示到数据表列中
dataGridView1.Rows[i].Cells[0].Value = arr_staff[0];
dataGridView1.Rows[i].Cells[1].Value = arr_staff[1];
dataGridView1.Rows[i].Cells[2].Value = arr_staff[2];
dataGridView1.Rows[i].Cells[3].Value = arr_staff[3];
}
}
}
}
结语:
List<T>泛型集合表示可通过索引访问的对象强类型列表,它提供了用于对列表进行搜索、排序和操作的方法。相对于ArrayList类来说,List<T>泛型集合在大多数情况下执行的更好,并且是类型安全的,而且比数组更加灵活。
List<T>泛型集合增加数据时使用Add()方法,学会使用dataGridView控件显示数据,会使用Split()方法拆分字符串,会用foreach循环语句。
喜欢的请关注和收藏!
本文暂时没有评论,来添加一个吧(●'◡'●)