摘要:Windows Forms Use C# ListView with Sqldata
使用ListView 與 資料庫整合方式
出處 : http://social.msdn.microsoft.com/Forums/windows/en-US/4b7eb940-feb4-474c-99cd-ebaf6998620b/populate-listview-with-datareader?forum=winforms
Hi fralo,
To add ListViewItem to the ListView, you should first add columns to the ListView.
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Column1");
listView1.Columns.Add("Column2");
When you open a SqlConnection and use SqlDataReader to get data from database, you can use this way to populate the ListView.
try
{
sqlConn.Open();
sqlReader = sqlComm.ExecuteReader();
while (sqlReader.Read())
{
ListViewItem lvItem = new ListViewItem();
lvItem.SubItems[0].Text = sqlReader[0].ToString();
lvItem.SubItems.Add(sqlReader[1].ToString());
listView1.Items.Add(lvItem);
}
sqlConn.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
First create a ListViewItem instance(lvItem), Set the SubItems[0] with the first column of SqlDataReader, add a new SubItem with the second column value.
Second, add that instance(lvItem) to the ListView with "listView1.Items.Add(lvItem);"
If you have any problem, please feel free to tell me.
Sincerely,
Kira Qian
Please mark the replies as answers if they help and unmark if they don't.