我認爲我已經閱讀了這裏和MSDN上的每篇文章,但我認爲我是一個特例,因爲大多數文章和帖子似乎並沒有涵蓋我正在努力。C#:使用線程更新另一個類的表單屬性
我正在瀏覽一個Excel工作表並提取記錄並將其傳遞給他們,以便他們可以轉換爲不同的文件類型。我試圖使用線程,所以我不捆綁用戶界面,一切都很好,除了更新我在表單中的進度條。下面是需要更新的形式類:
public class ExcelItem : Form1
{
private string inFile { get; set; }
public ExcelItem(string file)
{
inFile = file;
}
public string getExcelData()
{
string result = "";
int numRec = 0;
int recCount = 0;
Excel.Application xlApplication;
Excel.Workbook xlWorkbook;
Excel.Worksheet xlWorksheet;
Excel.Range xlRange;
xlApplication = new Excel.Application();
xlWorkbook = xlApplication.Workbooks.Open(File, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(2);
xlRange = xlWorksheet.UsedRange;
int rCnt = xlRange.Rows.Count;
int cCnt = xlRange.Columns.Count;
//for (int k = 1; k <= xlWorkbook.Worksheets.Count; k++)
// MessageBox.Show("Found worksheet " + k);
// get the number of records in tne sheet and use numRec to set progress bar max
for (int i = 1; i <= xlRange.Rows.Count; i++)
{
for (int j = 1; j <= xlRange.Columns.Count; j++)
{
if ((((Excel.Range)xlWorksheet.Cells[i, j]).Value2 != null) && (((Excel.Range)xlWorksheet.Cells[i, j]).Value2.ToString() == "Date of Birth"))
{
numRec++;
//code for updating progress bar max would go here
}
}
}
// iterate through records in sheet, use recCount to set progress bar value and return records
for (int i = 1; i <= xlRange.Rows.Count; i++)
{
for (int j = 1; j <= xlRange.Columns.Count; j++)
{
if ((((Excel.Range)xlWorksheet.Cells[i, j]).Value2 != null) && (((Excel.Range)xlWorksheet.Cells[i, j]).Value2.ToString() == "Date of Birth"))
{
result += Environment.NewLine;
recCount++;
// code for updating progress bar value would go here
}
if ((((Excel.Range)xlWorksheet.Cells[i,j]).Value2 != null) && (((Excel.Range)xlWorksheet.Cells[i, j]).Value2.ToString() != ":"))
{
result += (string)((Excel.Range)xlWorksheet.Cells[i, j]).Value2.ToString() + Environment.NewLine;
}
}
}
return result;
}
}
}
返回的記錄是沒有問題的,只是更新之類的東西,進度條頭痛現在。到目前爲止,我已經嘗試了代表,backgroundworker,BeginInvoker和線程,但似乎無法獲得任何工作。預先感謝您的幫助。
我也試過。每次它拋出一個無窗口處理程序異常。 – qwrobins
檢查[Control.IsHandleCreated](http://msdn.microsoft.com/ru-ru/library/system.windows.forms.control.ishandlecreated.aspx)屬性。 'InitializeComponent()'後面開始線程嗎? – shfire