首页 新闻 会员 周边

类的方法中更新progressbar

0
悬赏园豆:50 [已解决问题] 解决于 2011-11-20 22:52

主窗体上放置progressbar和button,在另一个类的方法中进行数据处理,点击button是调用该方法,请问如何可以在方法中更新主窗体上的progressbar,以反映数据处理的进度

lamy的主页 lamy | 初学一级 | 园豆:0
提问于:2011-11-17 15:39
< >
分享
最佳答案
1
    public partial class Form1 : Form
{
public Form1() {
InitializeComponent();
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = 100;
this.progressBar1.Step = 1;
}

private void button1_Click(object sender, EventArgs e) {
var myclass = new MyClass();
myclass.MyMethod(() =>
{
progressBar1.Invoke(new Action(() =>
{
this.progressBar1.PerformStep();
}));
});
MessageBox.Show("Done");
}
}
    public class MyClass
{
public void MyMethod(Action action) {
for (int i = 0; i < 100; i++) {
System.Threading.Thread.Sleep(100);
action();
}
}
}

是不是很简单?做C/S要多写匿名委托啊,多用Action<>和Func<>.

收获园豆:25
zhangweiwen | 小虾三级 |园豆:904 | 2011-11-17 17:47
其他回答(1)
1

在你说的“另一个类”中定义一个事件,就方便了。还是给你个简单的示例吧。

 public partial class Form1 : Form
{
Class1 class1 = new Class1();
public Form1()
{
InitializeComponent();
//注册事件
class1.OnProgressChanged += ProgressChanged;
}

private void button1_Click(object sender, EventArgs e)
{
Action action = new Action(class1.MyMethod);
action.BeginInvoke(null, null);
}
//这个方法就是执行更改进度条的
void ProgressChanged(int current,int max)
{
this.Invoke((Action) delegate
{ this.progressBar1.Value = current*this.progressBar1.Maximum/max; });

}
}

public class Class1
{
//定义事件
public Action<int, int> OnProgressChanged;
//测试的方法
public void MyMethod()
{
int count = 120;//模拟这个方法要处理120个东西
for (int i = 1; i <= count; i++)
{
//这里sleep是模拟你在处理数据
System.Threading.Thread.Sleep(100);

//处理完数据就把处理了多少数据发送到主界面上去更改进度条
if (OnProgressChanged != null)
{
OnProgressChanged(i, count);
}
}
}
}
收获园豆:25
LCM | 园豆:6876 (大侠五级) | 2011-11-17 16:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册