TreeView和DataGridView控件组合使用

TreeView和DataGridView控件组合使用

2023年6月22日发(作者:)

TreeView和DataGridView控件组合使⽤有时候会遇到将TreeView和DataGridView控件组合起来使⽤的需求。表结构类似于这样: 其中id为主键,pre为⽗级ID,这样的表结构可以⽣成TreeView.如下图现在要将这两个控件组合起来使⽤,可以根据TreeView的节点展开和收缩在DataGridView中显⽰不同的⾏。TreeView全部展开后如下图:TreeView部分收缩后见下图:以下是部分代码:具体⽰例⼤家可以到我的⽹站去下载,现在的问题是⽆法实现排序功能,希望⾼⼿给与指点。 1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 } 7 ///

8 /// 存放数据源 9 /// 10 DataTable dt = new DataTable(); 11 private void Form1_Load(object sender, EventArgs e) 12 {

13 #region 数据源⽰例 14 ("id"); 15 ("value"); 16 ("dis"); 17 ("pre"); 18 (0, "00", "000", 0); 19 (1, "11", "111", 0); 20 (2,"22","222",1); 21 ("a", "a3", "a000", "a"); 22 ("b", "b2", "b111", "a"); 23 ("c", "c1", "c222", "a"); 24 #endregion 24 #endregion 25 creatTree(dt, treeView1); 26 creatDataGridView(dt, dataGridView1); 27 dersVisible = false; 28 ight = HeadersHeight+2; 29 = 5; 30 tableChange(); 31 } 32 ///

33 /// 填充DataGridView 34 /// 35 /// 36 /// 37 void creatDataGridView(DataTable dt,DataGridView dgv) 38 {

39 urce=tView;

40 //可以做⼀些其他事情。 41

42 } 43 ///

44 /// ⽤DataTable填充树 45 /// 46 /// 47 /// 48 void creatTree(DataTable dt,TreeView tv) 49 { 50 if ( == 0) return; 51

52

53 foreach (DataRow dr in ) 54 { 55

56 if (dr["id"].ToString() == dr["pre"].ToString()) 57 { 58

59 (dr["id"].ToString(), dr["id"].ToString()); 60

61 } 62 else 63 { 64 TreeNode[] t=(dr["pre"].ToString(),true); 65

66 if ( < 1) 67 return; 68 else 69 t[0].(dr["id"].ToString(), dr["id"].ToString()); 70 } 71

72 } 73 (0, "ID"); 74 [0].BackColor = ; 75 } 76

77

78

79

80 ///

81 /// 节点展开后改变DataGridView 82 /// 83 /// 84 /// 85 private void treeView1_AfterExpand(object sender, TreeViewEventArgs e) 86 { 87 tableChange(); 88 } 89 /// 89 /// 90 /// 节点收缩后改变DataGridView 91 /// 92 /// 93 /// 94 private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e) 95 { 96 tableChange(); 97 } 98 string s; 99 /// 100 /// ⽣成DataView的RowFilter101 /// 102 /// 103 public void GetNode(TreeNodeCollection tc)104 {105 foreach (TreeNode TNode in tc)106 {107 if (ble == false)108 {109 s += "id<>'" + + "' and ";110 }111 GetNode();112 }113 }114 /// 115 /// 根据当前显⽰的节点来控制DataGridView的内容显⽰。116 /// 117 void tableChange()118 {119 s = "";120 TreeNodeCollection tc = ;121 GetNode(tc);122 if(>4)123 s = ( - 4);124 ter = s;125 urce = tView;126 }127

128 }

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687383546a5987.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信