C#_以SQLDataReader为数据源,实现TreeView与ListView之间的动态绑定
public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection conn = new SqlConnection("Server=.;database=jxc;uid=sa;pwd=198910"); SqlCommand commd; SqlDataReader dataread = null; DataTable dt; ArrayList arraylist = new ArrayList(); private void Form1_Load(object sender, EventArgs e) { commd = new SqlCommand("select * from Operater",conn); conn.Open(); try { dataread = commd.ExecuteReader(); while(dataread.Read()) { string value = dataread.GetValue(1).ToString();//获取第二列的值 TreeNode node = new TreeNode(value); treeView1.Nodes.Add(node);//为treeView控件增加一个节点 object[] values = new object[dataread.FieldCount];//以读取到的字段数声明一个Object数组 dataread.GetValues(values);//将所有数据放到object数组中 arraylist.Add(values);//加入ArrayList中 } dt = dataread.GetSchemaTable();//获取表结构 if (dt != null) { foreach (DataRow dr in dt.Rows) { listView1.Columns.Add(dr["ColumnName"].ToString(), 100, HorizontalAlignment.Center);//ListView添加列头 } } dataread.Close(); } catch(SqlException ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { listView1.Items.Clear(); int index = treeView1.SelectedNode.Index;//选中节点的索引号 ListViewItem vi = new ListViewItem(); vi.Text = ((object[])arraylist[index])[0].ToString(); for (int i = 1; i < ((object[])arraylist[index]).Length; i++) { vi.SubItems.Add(((object[])arraylist[index])[i].ToString()); } listView1.Items.Add(vi); } }
转载请注明本文链接。版权所有©2010 李佳龙专栏,保留所有权利。