C# 请教:一个线程来 实现每秒 更新一次dataGridView
不用timer
一个Button 一个dataGridView
点击 button 然后开始线程 大体代码如下 但有问题,请求解决(最好能给出完整代码)
private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(bind_datatgrid));
t.Start();
}
protected void bind_datatgrid()
{
while (true)
{
string[] a ={ "aa","nn","cc"};
dataGridView1.DataSource = a;
Thread.Sleep(1000);
}
}
异常:执行 CreateHandle() 时无法调用值 Dispose()。
不用timer
一个Button 一个dataGridView
点击 button 然后开始线程 大体代码如下 但有问题,请求解决(最好能给出完整代码)
private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(bind_datatgrid));
t.Start();
}
protected void bind_datatgrid()
{
while (true)
{
string[] a ={ "aa","nn","cc"};
dataGridView1.DataSource = a;
Thread.Sleep(1000);
}
}
异常:执行 CreateHandle() 时无法调用值 Dispose()。
而是要调用this.Invoke()
2.不知道楼主需要的是不是精确的每隔1秒,像你这种Thread.Sleep(1000);肯定就超过1秒了,
可以使用Envirement.TickTime(好像是)来判断, 简易版的直接使用backgroundworker
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(bind_datatgrid));
}
else
{
while (true)
{
string[] a = { "aa", "nn", "cc" };
dataGridView1.DataSource = a;
Thread.Sleep(1000);
}
}
}
{
while (true)
{
string[] a = { "aa", "nn", "cc" };
Invoke(new Action<object>(UpdateSource), a);
Thread.Sleep(1000);
}
}protected void UpdateSource(object a)
{
dataGridView1.DataSource = a;
}不过你这1秒更新一次好像有点频繁了
{
while (true)
{
string[] a = { "aa", "nn", "cc" };
Invoke(new MethodInvoker(delegate()
{
dataGridView1.DataSource = a;
}));
Thread.Sleep(1000);
}
}
麻烦你自己也动动脑子,别单一个“错”字就贴上来了。
Invoke(new Action <object>(UpdateSource), a);
不管用什么版本 上边的代码没有错误?
”麻烦你自己也动动脑子“ 这话咋这么刺耳呢?
Invoke我没有用过,对委托也不熟悉,
俺是新手,俺的思维范围小,俺只能在俺的有限范围里面进行操作
如果能知道或者找到解决方案 我会乱发帖?
哪向您这么厉害!问题没解决之前 我用了ListBox来替代dataGridView,效果有了,
但是如果像 Excel那样显示(有标题,下边跟内容) 不是很整齐
现在7楼帮我解决了 谢喽~