日期:2014-05-19  浏览次数:21463 次

C# winForm编程 菜鸟级问题
Form1类中含有一个treeview结构
点击form1的button按钮
弹出Form2类的一个窗口form2
该窗口负责接收一些文件信息     并创建一个新文件
然后怎么能够在form1中的treeview中增加一个新节点

form1的treeview   在Form2   类中不可见
错误提示   找不到treeview的上下文

望达人指点

谢谢

------解决方案--------------------
可以返回个参数,然form1的treeview 从新加载就可以
------解决方案--------------------
关于窗体间的数据交互,可以用委托,方法,public属性,事件等都可以实现,具体可以看我的Blog,
http://blog.csdn.net/yumanqing/archive/2006/10/23/1346272.aspx
http://blog.csdn.net/yumanqing/archive/2006/10/23/1346272.aspx
------解决方案--------------------
你把这个treeview设为public就可以
默认是private
窗口的属性列表里有modifiers,就是这个设为public

也可以把Form1里treeview的引用做为参数传给Form2
------解决方案--------------------
类似:
窗体互相引用增加了 耦合 度. 建议楼主用 Delegate+Event, 如下是实例:
1 定义一个公用的委托
public delegate void DataSourceAddDelegate();
2 中间类:
public class MyDataSource
{
public static ArrayList m_ArrayList = new ArrayList();
public static event DataSourceAddDelegate DataSourceAddEvent;

public static void Add(string str)
{
m_ArrayList.Add(str );
if (DataSourceAddEvent != null)
DataSourceAddEvent();
}
}

3 主窗体 Form1:
public Form1()
{
InitializeComponent();
MyDataSource.DataSourceAddEvent += new DataSourceAddDelegate(RefreshListBox);
}

private void RefreshListBox()
{
this.listBox1.DataSource = null;
this.listBox1.DataSource = MyDataSource.m_ArrayList;
}

private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}

4 Form2
private void button1_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(this.textBox1.Text))
{
MyDataSource.Add(this.textBox1.Text);
this.textBox1.Text = " ";
this.textBox1.Focus();
}
}