我想使用下面的代碼在datagridview中顯示列表的內容。如何將我的列表<string>綁定到datagridView?
List<string> data = new List<string>();
dataGridView1.DataSource = data;
我將我的數據添加到backgroundWorker中的列表中。如果我改變列表到的BindingList,我得到一個錯誤說
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
但是如果我使用List,我得到在DataGrid顯示它第三列只包含字符串爲每個legth進入類別。
有誰知道如何使用BackgroundWorker獲取datagrid以顯示字符串內容而不是字符串長度?
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;
}
顯示你的代碼的其餘部分,特別是你的待辦事項工作方法以及如何將列表傳遞給BG工作人員 – DGibbs 2013-04-22 13:31:21
在將數據分配給DataSource之前,您是否正在等待數據完成添加到列表中? – 2013-04-22 13:32:03
已發佈代碼 – 2013-04-22 13:34:38