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();
完。