【发布时间】:2014-07-07 00:54:10
【问题描述】:
我创建了一个应用程序,每当成功发送电子邮件时,它就会更新日志表单。我的代码是这样的:
mailSender.cs
void Serche()
{
{
//perform thread background ip scanner
}
if (InvokeRequired){
this.Invoke(new MethodInvoker(delegate
{
sendReport();
}));
}
}
public void sendReport()
{
//some codes to trigger time schedule to send report
ExportToExcel(filePath);
int milliseconds = 2000;
Thread.Sleep(milliseconds);
sendMail(filename);
}
private void sendMail(string filename)
{
string getFilePath = @"D:\Report\" + filename;
string status = "send";
try
{
// send email filename as attachment
}
catch (Exception ex)
{
status = "Fail";
}
sendMailReport(filename, DateTime.Now, mailStat);
}
private void sendMailReport(string fileName, DateTime dateDelivered, string status)
{
//mailLog updateLogs = new mailLog();
updateLogs.updateMailLogs(fileName,dateDelivered,status);
}
mailLog.cs
public void updateMailLogs(string _fileName, DateTime _dateDelivered, string _status)
{
int num = dataGridView1.Rows.Add();
dataGridView1.Rows[num].Cells[0].Value = _fileName;
dataGridView1.Rows[num].Cells[1].Value = _dateDelivered;
dataGridView1.Rows[num].Cells[2].Value = _status;
dataGridView1.Refresh();
}
我已经逐行调试代码,发现所有参数都在我的 updateMailLogs 方法中成功检索,但不知道为什么它没有更新我的 datagridview。有谁知道为什么?请指教。
已解决
感谢@shell,他启发了我这个问题的答案。
问题:-
1- 如果表单已经打开,那么我无法创建另一个 mailLog 表单对象并调用 updateMailLogs 方法。
2-这不会更新您的网格数据。因为两个对象引用不同。
解决方案:-
1-需要从当前加载的mailLog表单对象中调用该方法。
private void sendMailReport(string fileName, DateTime dateDelivered,string status)
{
if (Application.OpenForms["mailLog"] != null)
((mailLog)Application.OpenForms["mailLog"]).updateLogs.updateMailLogs(fileName,dateDelivered,status);
}
【问题讨论】:
-
如果你这样做有什么不同
dataGridView1.Rows.Add(_fileName, _dateDelivered, _Status);[我从来没有用这种方式手动刷新...] -
@AustinFrench 是的,我已经用那个方法绑定了,但结果还是一样。它没有刷新数据网格视图。
-
嗯,@Ren 你在尝试吗? dgv 是否正好有 3 列?我从一个带有假属性的按钮中使用了你的方法(复制粘贴),没有问题......
-
@AustinFrench 是的,我已经仔细检查了这些列,而且我正好有 3 个。如果这两个 mailSender.cs 和 mailLog.cs 都是不同的分隔形式,也许会有影响?如果我错了,请纠正我。
-
应该没问题,但要澄清一下,任何地方都没有 try、catch 或 finally 语句来捕捉这个?
标签: c# winforms datagridview