我有一个可以登录的表单,可能需要一段时间才能将数据加载到表单中。因此,我想在加载表单时创建一个带有进度条的单独表单(loadScreen.cs)。我在loadScreen.cs表单中尝试了这个:
private void Form1_Load(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged +=
new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
int percentFinished = (int)e.Argument;
while (!worker.CancellationPending && percentFinished < 100)
{
percentFinished++;
worker.ReportProgress(percentFinished);
System.Threading.Thread.Sleep(50);
}
e.Result = percentFinished;
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
我已经读过,worker_DoWork方法应该具有加载时间更长的代码。因为我的按钮在Form1中,所以我不知道如何处理这个问题。当它被点击时,我会带着
进入另一个班级 private void signIn_Click(object sender, EventArgs e)
{
var logIn = new LogIn(this);
logIn.checkUserInput(this);
}
然后我执行加载某些东西的操作。如何连接一切?我需要帮助!
答案 0 :(得分:1)
我实际上正在为这类事情创建一个通用对话。它没有及时准备好对你有用,但我建议你按照类似的方针行事。创建你的&#34; Loading&#34;对话,以便它接受委托并在DoWork
事件处理程序中调用它。然后,主窗体可以包含一个执行工作的方法,您可以将该方法的委托传递给对话。我将发布一个非常基本的例子。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable table;
private void button1_Click(object sender, EventArgs e)
{
var work = new Action(GetData);
using (var f2 = new Form2(work))
{
f2.ShowDialog();
this.dataGridView1.DataSource = this.table;
}
}
private void GetData()
{
this.table = new DataTable();
using (var adapter = new SqlDataAdapter("SELECT * FROM MyTable", "connectionstring here"))
{
adapter.Fill(table);
}
}
}
public partial class Form2 : Form
{
private Action work;
public Form2(Action work)
{
InitializeComponent();
this.work = work;
}
private void Form2_Load(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.work();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
请注意,在使用数据适配器时没有真正的方法来衡量进度,因此在这种情况下您只能真正显示选框进度条。