实现效果:
知识运用:
TreeView控件中的Nodes集合的Add方法
实现代码:
private void init() { treeView1.ShowLines = true; treeView1.ImageList = imageList1; try { string P_Connection = string.Format( @"Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|" + @"Database1.mdf;Integrated Security=True;User Instance=True"); SqlConnection P_sqlConnection = new SqlConnection(P_Connection); P_sqlConnection.Open(); SqlCommand P_sqlCommand = new SqlCommand( "select * from fruit", P_sqlConnection); SqlDataReader P_Read = P_sqlCommand.ExecuteReader(); while (P_Read.Read()) { TreeNode tn = new TreeNode("商品编号: " + P_Read[0].ToString(), 0, 1); tn.BackColor = Color.Red; tn.Nodes.Add(",", "产品名称: " + P_Read[1].ToString(), 1, 2); tn.Nodes.Add(",", "产品售价: " + P_Read[2].ToString(), 2, 3); tn.Nodes.Add(",", "享受包邮: " + P_Read[3].ToString(), 3, 4); treeView1.Nodes.Add(tn); } P_sqlConnection.Close(); treeView1.ExpandAll(); } catch (Exception ex) { MessageBox.Show("连接时出错: " + ex, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }