C# listbox continuous loop - c#

can i make this loop continue in such a way that after last item in listbox to go to the first one and so on...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
string queryhere = listBox1.Items[i].ToString();
this.SetTextappend("" + queryhere + "\n");
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 1);
}
}
}
}
Any help would be greatly appreciated!
Thank you for all the answers
it seems that my list was going backwads so i must replace
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
with
for (int i=0;i<ListBox1.Items.Count;i++)

You are counting down so I think it is "after the first one, go to the last (again)".
Your for-loop can become:
int i = 0;
for(;;) // or while(true)
{
if (i <= 0)
i = listBox1.Items.Count;
i -= 1;
if (worker.CancellationPending)
{
...
}
}
But I notice you are reading from a ListBox inside a bgw, that is not thread-safe. Even if it may appear to work, when the ListBox changes you could get null values or exceptions. Very infrequently.
Edit
And going the other way is even easier:
int i = -1;
for(;;) // or while(true)
{
i = (i + 1) % listBox1.Items.Count;
if (worker.CancellationPending)
{
...
}
}

Something like this ?
BackgroundWorker worker = sender as BackgroundWorker;
bool go = true;
while(go)
{
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
go = false;
break;
}
else
{
string queryhere = listBox1.Items[i].ToString();
this.SetTextappend("" + queryhere + "\n");
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 1);
}
}
}
}

int N = listbox1.Items.Count;
for (int i=N-1; !worker.CancellationPending; i = (i+N-1) % N )
{
// this weird calculation i=(i+N-1)%N is because I'm not sure whether C#
// divides negative integers properly (so that the remainder is non-negative)
// It could be i=(i-1)%N .
string queryhere = listBox1.Items[i].ToString();
this.SetTextappend("" + queryhere + "\n");
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 1); // by the way, there should be a percentage.
// You better revise the progress reporting.
}
e.Cancel = true;

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (worker.CancellationPending != true)
{
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if(worker.CancellationPending != true)
{
string queryhere = listBox1.Items[i].ToString();
this.SetTextappend("" + queryhere + "\n");
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i * 1);
}
else
{
break;
}
}
}
e.Cancel = true;
}

Related

Display only Even numbers in C#, using Windows Forms

I think this is a very easy answer and I understand that you enter something like this get an even number:
if (i % 2 == 0)
But I am just struggling to figure out how to slot it into my current code that I have here...
I have a form like so:
I am double clicking the 'Show Numbers' button
And I want the user to click the show numbers button and it only spits out even numbers, regardless if the box is checked or not.
namespace CHECK_BOXES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
if (checkBox1.Checked)
{
for (int i = 1; i <= 20; i++)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
else
{
for (int i = 20; i >= 1; i--)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
}
}
}
Would appreciate any help.
Thank you
Try with this function:
public bool IsEven(int value)
{
return value % 2 == 0;
}
and then update your for each loop with the following statement:
for (int i = 1; i <= 20; i++)
{
if (IsEven(i))
{
textBox1.Text += i.ToString() + "\r\n";
}
}
Or just easily increment i in for loop with 2.
Just do "double"-steps.
for (int i = 0; i <= 20; i += 2) { // <- pay attention, i will be incremented by 2
textBox1.Text += i.ToString() + "\r\n";
}
could be one line with Linq
textBox1.Text = string.Join("\r\n", Enumerable.Range(0, 20)
.Where((_, index) => index % 2 == 0).Select(x => x));

Why Is This Code Running Longer Character Combinations Than Necessary?

I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}

Wait 20 Seconds In Timer Before Executing Next Line Without Thread.Sleep.C#

I'm trying to wait for 20 seconds before adding + 1 value to i (Int), But i want to do it without Thread.Sleep.
This is my code, By the way I'm not a Pro programmer.
private void Refresh_App_TimerNH_Tick(object sender, EventArgs e)
{
label18.Text = "Timer Activated";
int i = 0;
i = i + 1;
if (i == 16)
{
i = 0;
}
else
{
}
if (i == 1)
{
webBrowser1.Refresh();
userIdLabel1.BackColor = Color.Red;
label20.Text = "+1";
//**i want to add 20 second gap here**
i = i + 1;
}
else
{
}
if (i == 2)
{
webBrowser2.Refresh();
userIdLabel2.BackColor = Color.Red;
label20.Text = "+2";
i = i + 1;
}
else
{
}
if (i == 3)
{
webBrowser3.Refresh();
userIdLabel3.BackColor = Color.Red;
label20.Text = "+3";
i = i + 1;
}
else
{
}
if (i == 4)
{
webBrowser4.Refresh();
userIdLabel4.BackColor = Color.Red;
label20.Text = "+4";
i = i + 1;
}
else
{
}
if (i == 5)
{
webBrowser5.Refresh();
userIdLabel5.BackColor = Color.Red;
label20.Text = "+5";
i = i + 1;
}
else
{
}
if (i == 6)
{
webBrowser6.Refresh();
userIdLabel6.BackColor = Color.Red;
label20.Text = "+6";
i = i + 1;
}
else
{
}
if (i == 7)
{
webBrowser7.Refresh();
userIdLabel7.BackColor = Color.Red;
label20.Text = "+7";
i = i + 1;
}
else
{
}
if (i == 8)
{
webBrowser8.Refresh();
userIdLabel8.BackColor = Color.Red;
label20.Text = "+8";
i = i + 1;
}
else
{
}
if (i == 9)
{
webBrowser9.Refresh();
userIdLabel9.BackColor = Color.Red;
label20.Text = "+9";
i = i + 1;
}
else
{
}
if (i == 10)
{
webBrowser10.Refresh();
userIdLabel10.BackColor = Color.Red;
label20.Text = "+10";
i = i + 1;
}
else
{
}
if (i == 11)
{
webBrowser11.Refresh();
userIdLabel11.BackColor = Color.Red;
label20.Text = "+11";
i = i + 1;
}
else
{
}
if (i == 12)
{
webBrowser12.Refresh();
userIdLabel12.BackColor = Color.Red;
label20.Text = "+12";
i = i + 1;
}
else
{
}
if (i == 13)
{
webBrowser13.Refresh();
userIdLabel13.BackColor = Color.Red;
label20.Text = "+13";
i = i + 1;
}
else
{
}
if (i == 14)
{
webBrowser14.Refresh();
userIdLabel14.BackColor = Color.Red;
label20.Text = "+14";
i = i + 1;
}
else
{
}
if (i == 15)
{
webBrowser15.Refresh();
userIdLabel15.BackColor = Color.Red;
label20.Text = "+15";
i = i + 1;
}
else
{
}
if (i == 16)
{
webBrowser16.Refresh();
userIdLabel16.BackColor = Color.Red;
label20.Text = "+16";
i = i + 1;
}
else
{
}
Refresh_App_TimerNH.Stop();
label18.Text = "Timer De-Activated";
Refresh_App_TimerNH.Start();
}
I think it might be easy but not for me, Because i'm new to c#
First off, Tim S's answer -- break up your logic into smaller chunks and simplify the timer logic -- is good. But to answer your specific question, which was "how do I delay between statements without Sleep", is: make the method async and then use await Task.Delay(...).
You are right to avoid Sleep; using it is a bad programming practice, and will hang your application. await Task.Delay does an asynchronous wait -- that is, the method returns immediately, the app keeps on processing UI messages, and when the delay is done, the program schedules the remainder of the method to execute later.
Note that during an asynchronous wait, by design messages keep on getting processed. If one of those messages causes your event handler to run again then you can get into the very confusing situation of having multiple control points in the same non-recursive method. Try to avoid that.
Right now your logic is convoluted, and probably very different from what you want it to do.
Your code will be much simpler if you put your webBrowserX and userIdLabelX items in some sort of list together.
public class MyPair
{
public WebBrowser WebBrowser { get; set; }
public Label UserIdLabel { get; set; }
}
private List<MyPair> pairs;
private int refreshIndex = 0;
private void StartTimer()
{
pairs = // populate pairs somehow
refreshIndex = 0;
var timer = new System.Windows.Forms.Timer();
timer.Interval = 20000
timer.Tick += MyTickHandler;
timer.Start();
label18.Text = "Timer Activated";
}
private void MyTickHandler(object sender, EventArgs e)
{
pairs[refreshIndex].WebBrowser.Refresh();
pairs[refreshIndex].UserIdLabel.BackColor = Color.Red;
label20.Text = "+" + (refreshIndex + 1);
refreshIndex = (refreshIndex + 1) % pairs.Count;
}
Note that this timer never deactivates, it loops through the list of pairs repeatedly.

How to search and replace words in a WPF TextBox?

I've found several examples that do this but with richTextBox instead. Is it even possible to replace words in a multi-line TextBox?
you can do this for searchin' the next word automatically in textbox
int t = 0;
private void FindNext(object sender, RoutedEventArgs e)
{
for (int i = t; i < NoteText.Text.Length-SearchBar.Text.Length; i++)
{
string x = "";
for (int j = 0; j < SearchBar.Text.Length; j++)
{
if(SearchBar.Text[j] == NoteText.Text[i+j])
{
x += NoteText.Text[i + j] + "";
}
else
{
x = "";
}
}
if(x == SearchBar.Text)
{
t = i+1;
NoteText.Focus();
NoteText.SelectAll();
NoteText.Select(i, SearchBar.Text.Length);
break;
}
if(i==NoteText.Text.Length - SearchBar.Text.Length - 1)
{
MessageBox.Show("The search was completed");
t = 0;
}
s = t;
}
}

Analogy between list_view_SelectedIndexChanged and list_box_SelectedIndexChanged

I have a handler for list_box:
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Text == "Question №" + (i + 1))
{
this.ShowOnePanel(i);
iter = i;
break;
}
}
}
and for list_view:
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Items[i].Text == "Question №" + (i + 1))
{
this.ShowOnePanel(i);
iter = i;
break;
}
}
}
It works for listbox, but doesn't work for listview. Why?
P.S. ShowOnePanel is my method, that shows one of the panels with question.
if (list_answers.Items[i].Text == "Питання №" + (i + 1))
I guess it's "question" not "Питання"
EDIT
private void list_answers_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < tasks.Count; i++)
{
if (list_answers.Items[i].Selected == true) // find selected item
{
if (list_answers.Items[i].Text == "Question №" + (i + 1)) // check it's content
this.ShowOnePanel(i);
iter = i;
break;
}
}
}

Categories