tags:

views:

159

answers:

1

There is a functionality in my module, where the user can scan the number of serial ports in the system and when the user clicks "Auto scan" button, the code will have to go through each serial port and send a test message and wait for the reply.

I am using Progress bar control to show process of autoscan. For which i need to pass the value to "x" and "Y" in my code to update the bar. How can i pass the value since my code is already in a foreach loop for getting the serialports.

Y = should pass the value of total number of serial ports X = should iterate through each port and pass the value

Hope i am clear with req.

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string strAckData = "";

        foreach (SerialPort sp in comPortsList)
        {
            sp.Open();
            string sendData = "Auto scan";
            sp.Write(sendData);
            strAckData += "Connection live on port " + sp.ReadExisting() + "\n";
            sp.Close();

            double dIndex = (double)x; **//How to pass the value here ?**
            double dTotal = (double)y; **//How to pass the value here ?**
            double dProgressPercentage = (dIndex / dTotal);
            int iProgressPercentage = (int)(dProgressPercentage * 100);

            // update the progress bar
            backgroundWorker1.ReportProgress(iProgressPercentage);

        }
        richTextBox1.Invoke(new MethodInvoker(delegate { richTextBox1.Text = strAckData; }));
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ProgressBar.Value = e.ProgressPercentage;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        StatusLabel.Text = "Auto Scan completed";
    } 
+1  A: 

You can get the number of ports from your comPortsList variable. Then the index is just a matter of incrementing a loop variable:

double dTotal = (double)(comPortsList.Count);
double dIndex = 0;

foreach (SerialPort sp in comPortsList)
{
  // talk to serial port as at the moment

  dIndex = dIndex + 1;  // or ++dIndex to be more concise
  double dProgressPercentage = dIndex / dTotal;
  // etc.
}
itowlson
@itowlson, to be more clear.. Y should be the value of total number of available ports and X should be the value of port which is opened at that time. In that case, X is not a constant value. The value of X changes every time the code executes sp.open()
Anuya
I've updated my answer to reflect this. Sorry for the misunderstanding. I'm still not sure I've exactly grasped what you mean by the "value" of a port though -- apologies if I'm still off beam.
itowlson