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));
Related
How can I get the value of the selected index in a CheckedListBox. I tried via through an if condition and switch cases, but it is not working as expected.
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (checkedListBox1.GetItemCheckState(0)==CheckState.Checked)
{
richTextBox1.Font = new Font(richTextBox1.Font, FontStyle.Bold);
}
}
i think you can use
checkedListBox1.CheckedIndices
Something like
foreach(int index in checkedListBox1.CheckedIndices)
{
if(index == 1)
{
//do something
}
}
Try this:
if(checkedListBox1.CheckedItems.Count != 0)
{
// If so, loop through all checked items and print results.
string s = "";
for(int x = 0; x <= checkedListBox1.CheckedItems.Count - 1 ; x++)
{
s = s + "Checked Item " + (x+1).ToString() + " = " + checkedListBox1.CheckedItems[x].ToString() + "\n";
}
MessageBox.Show (s);
}
I'm trying to display 5 scores in an array, but unfortunately all I get in the message box for the results is 0.
Any help would be appreciated.
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
when the add button is clicked the scores are stored in the array up to 5 times.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}
You keep overwriting message in this loop:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
So it's only ever going to show the last value. You probably want to append to it instead:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}
How can I do a counter in my Windows Form for count row many rows was read ?
When I execute my Windows Form this counter are shown just when the application processed every data.
Sample Code
public Form1()
{
InitializeComponent();
setMessage(string.Empty, this.lblErro);
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= xmlnode.Count - 1; i++)
{
int cont = i;
ThreadPool.QueueUserWorkItem(_ =>
{
setMessage(++cont + " of " + xmlnode.Count, this.lblCounter);
});
}
void setMessage(string message, Label lbl)
{
if (InvokeRequired)
{
Invoke((MethodInvoker)(() => setMessage(message, lbl)));
}
else
{
lbl.Text = message;
}
}
}
I tryied the code above but without success. Still shown the message when the app processed all the data
You need to run this loop:
for (int i = 0; i <= xmlnode.Count - 1; i++)
{
...
}
off of the main UI thread. There are a number of ways to accomplish this, but I prefer the BackgroundWorker for whatever reason. You could do it like this:
BackgroundWorker _worker = new BackgroundWorker();
and then in the ctor:
_worker.DoWork += (s, e) =>
{
// place the entire for loop in here
}
and now when you're ready to run it then just do this:
_worker.RunWorkerAsync();
Try putting the loop inside:
ThreadPool.QueueUserWorkItem(_ => {
for (int i = 0; i <= xmlnode.Count - 1; i++)
{
int cont = i;
setMessage(++cont + " of " + xmlnode.Count, this.lblCounter);
}
});
Hi I have a button that displays results using for loop, I want to find the sum of all the numbers and write them into the textBox2. I don't know how to do it. I'm using Visual Studio 2012, .NET 4.5 Framework. Your help is appreciated. Thanks.
private void button2_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 1000; i++)
if (i % 21 == 0 || i % 5 == 0)
{
listBox2.Items.Add(i);
}
int sum = ??????? ;
textBox2.Text = sum.ToString();
}
I think this might be what you're looking for.
foreach(int i in listBox2.Items) {
sum += i;
}
However, if the list box is empty before this button click, try:
private void button2_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 1; i <= 1000; i++)
if (i % 21 == 0 || i % 5 == 0)
{
sum += i;
listBox2.Items.Add(i);
}
textBox2.Text = sum.ToString();
}
You can simply find the sum when You add the items.
int sum=0;
for (int i = 1; i <= 1000; i++)
if (i % 21 == 0 || i % 5 == 0)
{
listBox2.Items.Add(i);
sum+=i;
}
textBox2.Text = sum.ToString();
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;
}