1.部门列表显示listview
首先需要在listview中设定相关属性
打开这个
代码:
private void DeptForm_Load(object sender, EventArgs e) { //初始化列表 setListView(); } /// <summary> /// 初始化部门列表 /// </summary> private void setListView() { MySqlConnection mySqlConnection = null; try { mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course"); mySqlConnection.Open(); string sql = string.Format("select * from deptInfo"); MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection); MySqlDataReader dataReader = mySqlCommand.ExecuteReader(); while (dataReader.Read()) { string deptId = dataReader["deptId"].ToString(); string deptName = dataReader["deptName"].ToString(); ListViewItem item = new ListViewItem(deptId); item.SubItems.Add(deptName); listView1.Items.Add(item); } dataReader.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); //throw; } finally { mySqlConnection.Close(); } }
2.在1基础上添加条件查询
private void DeptForm_Load(object sender, EventArgs e) { //初始化列表 setListView(); } /// <summary> /// 初始化部门列表 /// </summary> private void setListView() { MySqlConnection mySqlConnection = null; try { mySqlConnection = new MySqlConnection("server=127.0.0.1;port=3306;user=root;password=123456;database=course"); mySqlConnection.Open(); string sql = string.Format("select * from deptInfo"); //添加条件查询 if(deptNameText.Text.Trim().Length != 0) { sql += string.Format(" where deptName like '%{0}%'", deptNameText.Text.Trim()); } MySqlCommand mySqlCommand = new MySqlCommand(sql, mySqlConnection); MySqlDataReader dataReader = mySqlCommand.ExecuteReader(); while (dataReader.Read()) { string deptId = dataReader["deptId"].ToString(); string deptName = dataReader["deptName"].ToString(); ListViewItem item = new ListViewItem(deptId); item.SubItems.Add(deptName); listView1.Items.Add(item); } dataReader.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); //throw; } finally { mySqlConnection.Close(); } } /// <summary> /// 部门查询功能 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //需要先清空列表中的内容,不然会直接添加到列表末尾 listView1.Items.Clear(); setListView(); }
标签:dataReader,string,C#,学习,item,new,mySqlConnection,deptName,winform From: https://www.cnblogs.com/hmy22466/p/17837659.html