我正在尝试使用以下代码在 datagridview 中显示列表的内容。
List<string> data = new List<string>();
dataGridView1.DataSource = data;
我正在将我的数据添加到 backgroundWorker 的列表中。如果我将List更改为BindingList,我会收到一条错误消息
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
但是,如果我使用列表,当显示数据网格时,我会得到第三列,它只包含类别中每个条目的字符串长度。
有谁知道在使用 BackgroundWorker 时如何让数据网格显示字符串内容而不是字符串长度?
private void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
importExcelFile();
}
private void importExcelFile()
{
// hard coded file name for testing.
TextFieldParser parser = new TextFieldParser(@"E:\\test.csv");
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
data.Add(field);
}
}
parser.Close();
}
private void loadFileToolStripMenuItem_Click(object sender, EventArgs e)
{
backgroundWorker1.DoWork += OnBackgroundWorkerDoWork;
backgroundWorker1.RunWorkerAsync();
}
private void OnBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
dataGridView1.DataSource = data;
}