[英]C# how to get the count on a pop message box?
我正在制作一個批量郵件發件人,它將從數據庫中獲取郵件地址。 一切正常,測試郵件正在發送,但只有在所有郵件發送后才會顯示成功消息。 我想要一個消息框或一個進度框來計算通過的郵件。 幫我添加一個消息排場來計算已發送的郵件。 這里是我用於發送郵件的代碼,請給我寫消息框的代碼以顯示計數 -
private void btnSendEmail_Click(object sender, EventArgs e){
string subject = txtSubject.Text;
string message = txtMessage.Text;
if (!txtFile.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(txtFile.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(txtFile.Text))
{
}
}
else
{
}
}
var con = "Data Source=Ashiq-pc;Initial Catalog=OfferMails;Integrated Security=True;MultipleActiveResultSets=True";
List<EmailModel> emailList = new List<EmailModel>();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from tbl_MailAdd where Flag=@Flag";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Flag", true);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
EmailModel emailModel = new EmailModel();
emailModel.ID = Convert.ToInt16(oReader["ID"]);
emailModel.EmailAdd = oReader["EmailAdd"].ToString();
emailModel.Flag = Convert.ToBoolean(oReader["Flag"]);
emailList.Add(emailModel);
}
myConnection.Close();
}
}
//return matchingPerson;
foreach (EmailModel email in emailList)
{
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("my mail", "my pass");
MailMessage msg = new MailMessage();
msg.To.Add(email.EmailAdd);
msg.From = new MailAddress("my from name");
msg.Subject = subject;
msg.Body = message;
if (!txtFile.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(txtFile.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(txtFile.Text))
{
//Add file in ListBox.
listAttch.Items.Add(file);
//System.Windows.Forms.MessageBox.Show("Files found: " + file, "Message");
Attachment data = new Attachment(file);
msg.Attachments.Add(data);
}
}
else
{
//listBox1.Items.Add(String.Format(“No files Found at location : {0}”, textBox1.Text));
}
}
//Attachment data = new Attachment(textBox_Attachment.Text);
//msg.Attachments.Add(data);
client.Send(msg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//for (int i = 0; i < emailList.Count; i++)
//{
// MessageBox.Show("i++");
//}
MessageBox.Show("Successfully Sent Message.");
}
首先,我只想說,在這里要求某人為您編寫此代碼有點令人不快。 但我知道你在問什么,所以我願意幫忙。
首先,消息框本身不會為此工作,因為消息框最終會停止線程,直到處理DialogResult
事件。 因此,話雖如此,您可能想要構建另一個表單(我假設您在此處使用 Windows 表單執行此操作。)來為您完成進度。 如果您希望它是一個計數器,那么您可以使用一個標簽來實現,該標簽在每封郵件發送時都會更改其文本。
因此,話雖如此,但是,如果您使用 Windows 窗體執行此操作,您將遇到的問題是該窗體在您的foreach
循環完成之前永遠不會更新。 這是因為 C# 處理線程使用的方式。
對於您想要完成的工作,您需要使用BackgroundWorker.
這允許您異步運行繁瑣的操作。
以下是您可以用來讓系統正常工作的示例:
//used to be a counter for your progress
int i_counter = 0;
//create a background worker instance
public BackgroundWorker bg_worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
//set this to true if you want to have an event where you can cancel the background task
bg_worker.WorkerSupportsCancellation = true;
//this is needed to actually show your progress, allows the background worker to report it is working
bg_worker.WorkerReportsProgress = true;
//assigns the "DoWork" and "ProgressChanged" Handlers to the background worker.
bg_worker.DoWork += new DoWorkEventHandler(bg_worker_DoWork);
bg_worker.ProgressChanged += new ProgressChangedEventHandler(bg_worker_ProgressChanged);
}
//Mail method
public void MailerMethod()
{
//all of the things you want to happen for your mailing methods
foreach(//your loop stuff in here)
{
//THIS NEEDS TO HAPPEN TO CAUSE THE COUNTER TO UPDATE
bg_worker.ReportProgress(i_counter);
}
}
//the stuff that you want done in the background
//fires when "RunAsync" is called by BackgroundWorker object.
private void bg_worker_DoWork(object sender, DoWorkEventArgs e)
{
//IN HERE IS WHERE YOU WANT YOUR EMAIL STUFF TO HAPPEN
bg_worker = sender as BackgroundWorker;
MailerMethod();//or just all of your mailing code, it looks nicer like this though
}
//fires when worker reports the progress has changed
//caused by "ReportProgress" method
private void bg_worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lb_counter.Text = Convert.ToString(i_counter);
}
//this is what will happen when the worker is done.
//you can have it do a alot of things, such as write a report, show a window, etc.
private void bg_worker_RunWorkComplete(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("DONE!", "DING DING!");
Application.Exit();
}
//button click event to start this shindig
private void bt_start_Click(object sender, EventArgs e)
{
//makes sure the background worker isn't already trying to run
if (!bg_worker.IsBusy)
{
//calls the DoWork event
bg_worker.RunWorkerAsync();
bt_start.Visible = false;
}
}
我可以指導您到這里獲取官方 MDSN 文檔嗎? 這里有一個關於如何設置BackgroundWorker
的基本教程。
希望這會有所幫助,讓我知道它是怎么回事。
使用進度條,其 Position 屬性設置為零,Max 屬性設置為您發送的電子郵件數量,Step 屬性設置為 1,除非您想每 10 封左右的電子郵件步進一次,否則您將在循環中使用 % 10以提高進度。 在您的循環中,只需增加 ProgresBar 的位置或調用 Step()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.