C#如何获取弹出消息框的计数?

时间:2016-03-26 15:03:36

标签: c# asp.net windows counter messagebox

我正在制作一个批量邮件发件人,它将从数据库中获取邮件地址。一切正常,测试邮件正在发送,但只有在发送完所有邮件后才会显示成功消息。我想要一个消息框或进度框来计算正在传递的邮件。帮我添加一条消息pomp来计算邮件发送的数量。这里是我用来发送邮件的代码,请给我写一下消息框的代码来显示计数 -

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.");

}

2 个答案:

答案 0 :(得分:1)

首先,我要说的是,要求有人为你编写这段代码,这里有点不好意思。但是我知道你在问什么,所以我愿意帮忙。

首先,消息框本身不适用于此,因为消息框最终会停止线程所在的位置,直到处理git worktree add second_path 事件为止。所以,为此,你可能想要构建另一个表单(我假设你在这里使用Windows Forms这样做。)为你做进展。如果您希望它是一个计数器,那么您可以使用在每封邮件发送时更改其文本的标签来执行此操作。

因此,有了这样说,但是,如果您使用Windows窗体执行此操作,您将遇到的问题是表单永远不会更新,直到您的 DialogResult循环结束。这是因为C#处理线程使用的方式。

对于您想要完成的任务,您需要使用foreach这允许您异步运行繁琐的操作。

以下是一个可用于使系统正常工作的示例:

BackgroundWorker.

我可以指导您here获取官方MDSN文档。 并here获取有关如何设置//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; } } 的基本教程。

希望这会有所帮助,让我知道它是怎么回事。

答案 1 :(得分:0)

使用进度条,其Position属性设置为零,Max属性设置为您要发送的电子邮件数,Step属性设置为1,除非您想要每10个左右发送一次电子邮件然后使用%10在你的循环中增加进度。在循环中只需增加ProgresBar的位置或调用Step()。