首页 新闻 会员 周边 捐助

如何实现 TreeView 与DataGridView的联动

0
悬赏园豆:40 [已解决问题] 解决于 2010-07-25 17:24

TreeView 和DataGridView分别放在A,B 两个不同的winform当中。

点击 A当中TreeView的不同节点,B中的DataGridView数据随之改变

希望高手提供代码

sjh的主页 sjh | 初学一级 | 园豆:10
提问于:2010-07-23 09:54
< >
分享
最佳答案
0

Form1:

 

 

代码
Form2 fr2 = new Form2();

private void Form1_Load(object sender, EventArgs e)
{
TreeNode tt
= new TreeNode("aa");
TreeNode t1
= new TreeNode("bb");
TreeNode t2
= new TreeNode("cc");
TreeNode t3
= new TreeNode("dd");
treeView1.Nodes.
Add(tt);
tt.Nodes.
Add(t1);
tt.Nodes.
Add(t2);
tt.Nodes.
Add(t3);


fr2.Show();

}

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{

string s
= treeView1.SelectedNode.Text;
fr2.ChooseTable(s);
}

 

 

 

Form2:

 

代码
public void ChooseTable(string s)
{
DataTable dtbb
= new DataTable();
DataColumn dcb1
= dtbb.Columns.Add("namebb", Type.GetType("System.String"));
DataColumn dcb2
= dtbb.Columns.Add("bid", typeof(int));
DataRow drb
= dtbb.NewRow();
drb
["namebb"] = "bb1";
drb
["bid"] = 11;
dtbb.Rows.
Add(drb);
drb
= dtbb.NewRow();
drb
["namebb"] = "bb2";
drb
["bid"] = 22;
dtbb.Rows.
Add(drb);

DataTable dtcc
= new DataTable();
DataColumn dcc1
= dtcc.Columns.Add("namecc", Type.GetType("System.String"));
DataColumn dcc2
= dtcc.Columns.Add("cid", typeof(int));
DataRow drc
= dtcc.NewRow();
drc
["namecc"] = "cc1";
drc
["cid"] = 111;
dtcc.Rows.
Add(drc);
drc
= dtcc.NewRow();
drc
["namecc"] = "cc2";
drc
["cid"] = 222;
dtcc.Rows.
Add(drc);

DataTable dtdd
= new DataTable();
DataColumn dcd1
= dtdd.Columns.Add("namedd", Type.GetType("System.String"));
DataColumn dcd2
= dtdd.Columns.Add("did", typeof(int));
DataRow drd
= dtdd.NewRow();
drd
["namedd"] = "dd1";
drd
["did"] = 1111;
dtdd.Rows.
Add(drd);
drd
= dtdd.NewRow();
drd
["namedd"] = "dd2";
drd
["did"] = 2222;
dtdd.Rows.
Add(drd);

DataTable dtaa
= new DataTable();
DataColumn dca1
= dtaa.Columns.Add("nameaa", Type.GetType("System.String"));
DataColumn dca2
= dtaa.Columns.Add("aid", typeof(int));
DataRow dra
= dtaa.NewRow();
dra
["nameaa"] = "aa1";
dra
["aid"] = 1;
dtaa.Rows.
Add(dra);
dra
= dtaa.NewRow();
dra
["nameaa"] = "aa2";
dra
["aid"] = 2;
dtaa.Rows.
Add(dra);


DataTable dt
= new DataTable();
switch (s)
{
case "aa":
this.dataGridView1.DataSource
= dtaa;
break;
case "bb":
this.dataGridView1.DataSource
= dtbb;
break;
case "cc":
this.dataGridView1.DataSource
= dtcc;
break;
case "dd":
this.dataGridView1.DataSource
= dtdd;
break;
default: break;

}
}
收获园豆:40
xihongshibeibei | 菜鸟二级 |园豆:386 | 2010-07-23 15:07
谢谢你的回答,你的代码没有问题,也可以正常运行,但是我的开始忘了说明,我的两个窗体到时再docking中,所有问题还是没有解决,谢谢
sjh | 园豆:10 (初学一级) | 2010-07-25 17:23
其他回答(1)
1

点击 A当中TreeView的不同节点向B中传递不同参数。

dege301 | 园豆:2825 (老鸟四级) | 2010-07-23 12:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册