C# · 12月 27, 2021

c# – 更新背景工作者winforms中的标签文本

我正在使用BackGroundWorker类在sqlserver中插入一些值.我有这个循环来插入值.我正在使用以下代码 public void bw_Convert_DoWork(object sender,DoWorkEventArgs e) { e.Result = e.Argument; for (int i = 0; i < fTable.Rows.Count; i++) { try { sqlCommand cmd = new sqlCommand(“INSERT INTO TBL_CDR_ANALYZER (LNG_UPLOAD_ID,DAT_START,LNG_DURATION,INT_DIRECTION,INT_CALL_DATA_TYPE,\n” + “TXT_TARGET_NUMBER,TXT_OTHER_PARTY_NUMBER,TXT_TARGET_IMSI,TXT_TARGET_IMEI,TXT_TARGET_CELL_ID,TXT_ROAMING_NETWORK_COMPANY_NAME) VALUES \n” + “(@UPLOAD_ID,@START_DATE,@DURATION,@DIRECTION,@CALL_TYPE,@TARGET_NUMBER,@OTHER_PARTY_NUMBER,@IMSI,@IMEI,@CELL_ID,@ROAMING_NAME)”,sqlCon); cmd.Parameters.Add(“@UPLOAD_ID”,sqlDbType.Int).Value = 1; cmd.Parameters.Add(“@START_DATE”,sqlDbType.DateTime).Value = fTable.Rows[i][“CallDate”]; cmd.Parameters.Add(“@DURATION”,sqlDbType.Int).Value = fTable.Rows[i][“CallDuration”]; cmd.Parameters.Add(“@DIRECTION”,sqlDbType.Int).Value = GetCallDirection(fTable.Rows[i][“CallDirection”].ToString()); cmd.Parameters.Add(“@CALL_TYPE”,sqlDbType.Int).Value = GetCallType(fTable.Rows[i][“CallType”].ToString()); cmd.Parameters.Add(“@TARGET_NUMBER”,sqlDbType.VarChar,25).Value = fTable.Rows[i][“TargetNo”]; cmd.Parameters.Add(“@OTHER_PARTY_NUMBER”,25).Value = fTable.Rows[i][“OtherPartyNo”]; cmd.Parameters.Add(“@IMSI”,50).Value = fTable.Rows[i][“IMSI”]; cmd.Parameters.Add(“@IMEI”,50).Value = fTable.Rows[i][“IMEI”]; cmd.Parameters.Add(“@CELL_ID”,50).Value = fTable.Rows[i][“CellID”]; cmd.Parameters.Add(“@ROAMING_NAME”,sqlDbType.NVarChar,255).Value = fTable.Rows[i][“RoamingCompany”]; sqlCon.open(); cmd.ExecuteNonQuery(); sqlCon.Close(); } catch (sqlException ex) { } finally { sqlCon.Close(); } bw_Convert.ReportProgress((100 * i) / fTable.Rows.Count); **Label1.Text = i.ToString() + “Files Converted”;** // getting error Here. } }

如何在这里更新Label1文本?

解决方法 这应该可以从后台线程更改GUI. Label1.Invoke((MethodInvoker)delegate { Label1.Text = i.ToString() + “Files Converted”;});