Με κομματια κωδικα ειναι δυσκολο(βαρετο) να καταλαβω τι παιζει. Το exception τι λεει? τεσπα αφου ξεμπερδεψες με το cross-thread δες το παρακατω κωδικα και προσπαθισε να τον φερεις στα μετρα σου.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace treeview
{
public partial class Form1 : Form
{
Thread t;
Random r;
List<string> users;
public Form1()
{
InitializeComponent();
t = new Thread(func);
r = new Random();
users = new List<string>() { "lola", "pipis", "nikos", "petros", "lila", "pila" };
treeView1.Nodes.Add(new TreeNode { Name = "Root", Text = "Users:" });
foreach (var item in users)
{
AddInRootNode(new TreeNode { Name = item + "_key", Text = item });
}
this.Load += delegate
{
t.Start();
};
}
//allo thread
void func()
{
for (int i = 0; i < 100; i++)
{
bool active = r.Next() % 2 == 0;//random bool
string key = users[r.Next(users.Count )] + "_key";//random key
UpdateNode(key, active);
Thread.Sleep(1000);
}
}
void AddInRootNode(TreeNode node)
{
var root = treeView1.Nodes.Find("Root", false).Single();
if (root == null)
throw new Exception("Den yparxei root");
root.Nodes.Add(node);
}
void UpdateNode(string nodeKey,bool active)
{
var nodeForUpdate = treeView1.Nodes.Find(nodeKey, true).Single();
if (nodeForUpdate == null)
throw new Exception("Den yparxei node me to key:" + nodeKey);
if (active)
nodeForUpdate.ForeColor = Color.Blue;
else
nodeForUpdate.ForeColor = Color.Red;
}
}
}