I have two WinForms (Setting
and frmMain
). I have a TreeView in Setting's form and I want to call its FillTree
method in the second form frmMain
.
I'm using the TreeView.Invoke
for the threading purposes.
Here is my code for TreeView filling data in Setting's form :
TreeNode parentNode;
public void FillTree(DataTable dtGroups, DataTable dtGroupsChilds)
{
treeViewGroups.Nodes.Clear();
if (dtGroups == null) return;
foreach (DataRow rowGroup in dtGroups.Rows)
{
parentNode = new TreeNode
{
Text = rowGroup["Groupname"].ToString(),
Tag = rowGroup["Groupid"]
};
treeViewGroups.Invoke(new Add(AddParent), new object[] { parentNode });
if (dtGroupsChilds == null) continue;
foreach (DataRow rowUser in dtGroupsChilds.Rows)
{
if (rowGroup["Groupid"] == rowUser["Groupid"])
{
TreeNode childNode = new TreeNode
{
Text = rowUser["Username"].ToString(),
Tag = rowUser["Phone"]
};
treeViewGroups.Invoke(new Add(AddParent), new object[] { childNode });
System.Threading.Thread.Sleep(1000);
}
}
}
treeViewGroups.Update();
}
public delegate void Add(TreeNode tn);
public void AddParent(TreeNode tn)
{
treeViewGroups.Nodes.Add(tn);
}
public void AddChild(TreeNode tn)
{
parentNode.Nodes.Add(tn);
}
FillTree
method from above code, I wants call it in my second form frmMain which I tried like so:
Settings settingsWindow;
public frmMain()
{
InitializeComponent();
settingsWindow = new Settings(this);
}
private void SomeMethod()
{
//Two DataTables (dt1 and dt2) are passed from frmMain form
settingWindow.FillTree(dt1, dt2);
}
When I call FillTree
method it show me error like this:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
I real wants to know, where should be handle TreeView's Invoke method in my second winform frmMain
?
I'm following these links (but no avail):
1) Populating TreeView on a Background Thread
2) How to add object in treeview from another thread
3) How can i invoke a method called from backgroundworker dowork event?
Edited for Visualizing Problem
I have tried it with TreeView its not working then I Tried it with ListBox but the problem is still same.
Problem: I've a method (which populate my ListBox) in WinForm settingsWindow
and I want to call that method in my second WinForm frmMain
.
Settings
form screenshot:
frmMain
form screenshot:
Problem GIF :
Settings form Code for ListBox Populating :
public void PopulateGroupListData(DataTable dt)
{
listGroups.DataSource = null;
listGroups.DisplayMember = "GroupName";
listGroups.ValueMember = "Groupid";
listGroups.DataSource = dt;
if (listGroups.Items.Count > 0)
listGroups.SelectedItem = listGroups.Items[0];
}
Calling PopulateGroupListData
in second form frmMain
's method:
void onCompleteReadFromServerStream(IAsyncResult iar)
{
/... some code
String[] arr1 = ServerMessage[1].Split('&');
string Groupid1 = arr1[0];
string GroupName1 = arr1[1];
GroupsList.Rows.Add(Groupid1, GroupName1);
settingsWindow.PopulateGroupListData(GroupsList);
/... some code
}