S
S
Sergey Polyntsev2014-11-27 01:14:29
Programming
Sergey Polyntsev, 2014-11-27 01:14:29

How to solve ListBox issue in C#?

I have such a problem. The program determines whether the given IP address is available, if it is available, then an entry is created in the ListBox with acc. IP address. I do it like this:

Ping pingSender = new Ping();
IPAddress address;
String str;
PingReply reply;
str = textBox1.Text + "." + textBox2.Text + "." + textBox3.Text + "." + textBox4.Text;
IPAddress.TryParse(str, out address);
reply = pingSender.Send(address);
if (reply.Status == IPStatus.Success)  listBox1.Items.Add(str);

There is no problem with this. The problem occurs when a range of addresses is checked. In theory, it should be like this: the address is checked, if it is available, it is displayed in the list, and then the trace is checked. the address. But it's not like that: available addresses are displayed only after checking all addresses. It happens that you wait half a minute, only then available addresses are displayed, and this is not convenient. How can this be fixed?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
cjey, 2014-11-27
@cjey

To handle windows rendering events in a long loop, use Application.DoEvents().

for (int i = 0; i < 100; i++)
{
                listBox1.Items.Add(i);
                Application.DoEvents();
                System.Threading.Thread.Sleep(1000);
}

R
Rsa97, 2014-11-27
@Rsa97

Move the check loop to a separate thread.

V
Vitaly Pukhov, 2014-11-27
@Neuroware

Rsa97 is right, but this is not such a trivial task for a beginner (a non-beginner knows what threads are and would not ask)
you can do this by stuffing all the code into void DoScan ()
further in the place where the code was put Thread t = new Thread (DoScan) ;
t.Start();
but that's not all, so there will be errors when adding an element to the list, so you need to replace
on the

BeginInvoke(new MethodInvoker(delegate
            {
               if (reply.Status == IPStatus.Success)  listBox1.Items.Add(str);
            }));

then there will be no problems, tk. this code will be executed on the main thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question