我编写了一个代码来将文本文件中的值传输到数据表。由于记录数量很多,我实现了一个进度条来查看状态。但它会引发一个错误,称为
“‘1’的值对‘值’无效。‘值’应该在‘最小值’和‘最大值’之间。”
你能帮我在循环中成功实现进度条吗?这是我使用的代码:
我已经用后台工作人员更新了我的编码。但它会引发一个错误,称为:
“创建窗口句柄时出错”
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog thisDialog = new OpenFileDialog();
DataTable dt = new DataTable();
DataRow dr = null;
if (thisDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text=thisDialog.FileName;
string file1 = textBox1.Text;
//background worker
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync();
}
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
}
using (System.IO.StreamReader file = new System.IO.StreamReader(file1))
{
string line=String.Empty;
int lineno = 0;
while ((line = file.ReadLine()) != null)
{
if (line.Contains("DISKXFER"))
{
string dataLine = line.ToString();
string[] split = dataLine.Split(',');
int result = split.Length;
if (lineno == 0)
{
for (int x = 0; x < result; x++)
{
DataColumn dcss = new DataColumn(x.ToString(), Type.GetType("System.String"));
dt.Columns.Add(dcss);
}
if (dt.Rows.Count <= lineno)
{
dr = dt.NewRow();
dt.Rows.Add(dr);
}
dr = dt.Rows[lineno];
for (int x = 0; x < result; x++)
{
dr[x+1] = split[x];
}
}
else
{
if (dt.Rows.Count <= lineno)
{
dr = dt.NewRow();
dt.Rows.Add(dr);
}
dr = dt.Rows[lineno];
for (int x = 0; x < result; x++)
{
dr[x+1] = split[x];
}
}
lineno += 1;
}
}
}
}
dataGridView1.DataSource = dt;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string line;
string file1 = textBox1.Text;
using (System.IO.StreamReader file = new System.IO.StreamReader(file1))
{
int count = 0;
while ((line = file.ReadLine()) != null)
{
if (line.Contains("DISKXFER"))
{
backgroundWorker1.ReportProgress(count);
}
count += 1;
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}