ListView控件: (一) 生成一个ListView对象 listView1: - ListView listView1 = new ListView();
(二) listView1对象的属性
- //设置listView1的大小
- listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200));
-
- //展示ListView的所有信息
- listView1.View = View.Details;
-
- // 是否运行用户编辑
- listView1.LabelEdit = true;
- // 是否运行用户调整列的顺序
- listView1.AllowColumnReorder = true;
-
- // .这条语句在每一行的行头加个选择属性。
- listView1.CheckBoxes = true;
- //要选就全行选中
- listView1.FullRowSelect = true;
-
- // 展示分割线
- listView1.GridLines = true;
-
- // 对每一项进行排序
- listView1.Sorting = SortOrder.Ascending;
-
- //需要的时候显示滚动条
- listView1.Scrollable = true;
-
- //listView1的列的头部是否可点击,响应事件
- listView1.HeaderStyle = ColumnHeaderStyle.Clickable;
(三) 通过数据库给listview1添加项
- /*** 清空listView ***/
- listView1.Clear();
-
- // Create columns for the items and subitems.
- // -2 表示自动调节大小.
- listView1.Columns.Add("序号", -2, HorizontalAlignment.Left);
- listView1.Columns.Add("名称", -2, HorizontalAlignment.Center);
- listView1.Columns.Add("人数", -2, HorizontalAlignment.Center);
-
- /***连接数据库,显示信息***/
- MySQLConnection conn = null;
-
- //第一个参数:数据库名,第二个参数:数据库的用户名,第三个参数:密码
- //这里,group是我连接的数据库,root是数据库的用户名,第三个参数是密码,也为"root"
- conn = new MySQLConnection(new MySQLConnectionString("group", "root", "root").AsString);
-
- /**group_people是数据库下面的一个表**/
- MySQLCommand cmd = new MySQLCommand("select * from group_people", conn);
-
- //打开连接
- conn.Open();
-
- /**汉字编码问题。执行一遍之后,读出的汉字不乱码**/
- MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
- commn.ExecuteNonQuery();
-
- /**执行cmd语句,即查询语句**/
- MySQLDataReader reader = cmd.ExecuteReaderEx();
-
- int i = 0;
- while (reader.Read())
- {
- i++;
- ListViewItem item = new ListViewItem();
-
- item.SubItems.Clear();
-
- /**名称**/
- item.SubItems[0].Text = i.ToString();
- item.SubItems.Add(reader.GetString(0));
-
- /**人数**/
- string tempPeople = reader.GetString(1);
- string []tempArrayPeople = tempPeople.Split(' ');
- item.SubItems.Add(tempArrayPeople.Length.ToString());
-
- listView1.Items.Add(item);
- }
-
- conn.Close();
完。
|