I need help with timer and List.
List consist of collection of string say 5 or 6 at a time. Now, I want to display string one on label1 and it should wait for 5s and then display string 2 on label1. I have timer control and I am specifying my code in timer_tick event.
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
for (int i = 0; i < length; i++)
{
string _myStatus = myStatus[i];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
}
}
I have specify, Elapse = true and interval = 5000 but still I am not able to display one string at a time. In fact, I am getting last string only. I want to rotate the strings all time.
Can anyone help me.
That's because you're looping through all the strings each time the timer event fires.
Store your index in a private variable and use that instead.
private int _index = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
string _myStatus = myStatus[_index];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
if(_index == (myStatus.Length - 1))
_index = 0;
else
_index++;
}
Well it is doing just what you told it to. However, what you told it to do is not what you meant for it to do. Try this.
public class Form1 : Form {
private string[] statuses = { "A", "B", "C", "D", "E" }; // Init with proper values somewhere
private int index = 0;
private void OnTimerTick(object sender, EventArgs e) {
string status = statuses[index];
index++;
if (index == statuses.Length) { // If index = Array.Length means we're
// outside bounds of array
index = 0;
}
}
}
I'd create an int outside of the Tick to hold your position. Make sure you reset it back to 0 when you restart the process.
int MyPosition = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
if((MyPosition + 1) > length)
{
//Index Out of Range
}
else
{
string _myStatus = myStatus[MyPosition];
label1.Text = _myStatus
}
MyPosition++;
}
Related
I have a basic form with a button and a textbox to insert a number
I want to keep the number inserted in the first index of the array, then if I put another number and I click the button, I want that number to be stored in the second index of the array and so on
I have to make a loop to increment the index but if I use the loop, the first number I put in the box, it's going to be stored in all the indexes of the array
Here's my code (doesn't work)
public partial class EXERCISES_ARRAYS : Form
{
int[] numbers = new int[5];
private void btnAdd_Click(object sender, EventArgs e)
{
int i = 0;
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
for (int j = 0; j < 5; j++)
{
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
}
}
You want a List, rather than an array. That will take care of all of this for you:
public partial class EXERCISES_ARRAYS : Form
{
List<int> numbers = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
numbers.Add(int.Parse(txtInsertedValue.Text));
}
}
I don't think you need to add a for loop for this. Try this
int[] numbers = new int[5];
int i = 0;
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 6 years ago.
When I press the click event to add array values, it gives me an out of index exception error. I'd like to know why it's happening and how to fix it, thanks.
using System;
using System.Windows.Forms;
namespace ArrayTestCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double total = 0;
double average = 0;
double scoreInput = 0;
int countOfExams = 0;
double[] examScores;
double count = 0;
//field array declare
private void enterBtn_Click(object sender, EventArgs e)
{
countOfExams = int.Parse(numOfExamsTextBox.Text);
examScores = new double[countOfExams];
examLabel.Text = "Exam 1: ";
label1.Visible = false;
numOfExamsTextBox.Visible = false;
enterBtn.Visible = false;
examLabel.Visible = true;
examScoresTextBox.Visible = true;
addBtn.Visible = true;
}
private void addBtn_Click(object sender, EventArgs e)
{
examLabel.Text = "Exam " + (countOfExams +1) + ":";
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
examScoresTextBox.ResetText();
examScoresTextBox.Focus();
if(countOfExams >= examScores.Length)
{
MessageBox.Show("hoise vaya");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
Array.Clear(examScores, 0, examScores.Length);
ClearAll();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
public void ClearAll()
{
examLabel.Text = "Exam:";
examScoresTextBox.ResetText();
numOfExamsTextBox.ResetText();
}
private void calcBtn_Click(object sender, EventArgs e)
{
}
}
}
In the first line of your enterBtn_Click,
countOfExams = int.Parse(numOfExamsTextBox.Text);
I suppose you are using countOfExams as the total length of the array.
Later in the second line of your addBtn_Click,
examScores[countOfExams] = double.Parse(examScoresTextBox.Text);
countOfExams++;
I suppose you are using countOfExams to track the actual number of exams. Because countOfExams is already set to the length, it results in OutOfRangeException.
Thus, I suggest you to use another variable (e.g. a local variable) for the total length of the array,
var size = int.Parse(numOfExamsTextBox.Text);
examScores = new double[size];
double[] examScores; has been defined as array, which was never initialized if you are not calling enterBtn_Click first
Ideally,
You should first initialize/ check if it is initialized it by
double[] examScores = new double[<length>];
also, the counter starts from 0 and not 1
If you are not sure about the length or capacity, use List
I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?
private void btnAdd_Click(object sender, EventArgs e)
{
int points;
try
{
points = int.Parse(txtPoints.Text);
lstPoints.Items.Add(points);
txtPoints.Clear();
txtPoints.Focus();
if (lstPoints.Items.Count == 12)
{
txtPoints.Enabled = false;
btnAdd.Enabled = false;
}
if (lblResult.Text != "")
{
lblResult.Text = "";
}
}
catch
{
MessageBox.Show("Please enter only whole numbers");
txtPoints.Clear();
txtPoints.Focus();
}
}
private void btnAvg_Click(object sender, EventArgs e)
{
double total = 0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
total += (int)lstPoints.Items[i];
}
total /= lstPoints.Items.Count;
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
lstPoints.Items.Clear();
txtPoints.Enabled = true;
btnAdd.Enabled = true;
}
}
}
hope this works
private void getMax()
{
int max=0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
if(max<(int)lstPoints.Items[i])
{
max=(int)lstPoints.Items[i];
}
}
lblResult.Text = max.ToString();
}
}
private void getMin()
{
int min=(int)lstPoints.Items[0];
for (int i = 1; i < lstPoints.Items.Count; i++)
{
if(min>(int)lstPoints.Items[i])
{
min=(int)lstPoints.Items[i];
}
}
lblResult.Text = min.ToString();
}
}
There are two possiblities as I see:
1) When you are writing this:
lstPoints.Items.Add(points);
Instead of adding to List(Of Integer) use SortedList. So the
list will always have the sorted result sets.
2) Use Array.Sort() to sort the records.
Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).
Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.
Hope it helps!
im pretty new to C# and i want to make a cardgame. What i have is a list of cards (strings) with names like c6, s3, h11, d13 where the character represents the colour and the number represents the value. When pressing a button the program takes a random string from the list and displays it in a textbox. From there the point of the game is to guess if the next random card will have a higher value or a lower value then the previous card.
What i want to do is to take the string from the textbox and turn it into a int so that i can compare the value of the previous card with the new one. Only problem is how do i get rid of the c in c6 so i can convert it by using parse.
This is my code.
public partial class MainWindow : Window
{
static Random rndmlist = new Random();
Random rndm = new Random();
List<string> deck = new List<string>();
int score = 0;
public MainWindow()
{
InitializeComponent();
}
private void test_Click(object sender, RoutedEventArgs e)
{
//disregard this
foreach (string j in deck)
{
testbox.Text += j + ", ";
}
}
private void btnstart_Click(object sender, RoutedEventArgs e)
{
//this is where i add all the cards to the list
for (int i = 1; i <= 13;)
{
deck.Add("c" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("s" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("h" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("d" + i);
i++;
}
}
private void btnbegin_Click(object sender, RoutedEventArgs e)
{
//this is where i take a random card from the list and display it in textBox2
int r = rndmlist.Next(deck.Count);
textBox2.Text = ((string)deck[r]);
//disregard this
testbox.Text += ((string)deck[r]) + ", ";
deck.Remove((string)deck[r]);
}
private void btnhigh_Click(object sender, RoutedEventArgs e)
{
//this is where i want to compare the cards.
}
}
Thank you in advance for reading this. (:
I'd better create a class Card, which represents a card, with 2 properties: Color and Number and implemented method Card.ParseFromString()
Try this,
string SubString = MyString.Substring(1);
But take care if the string is empty, it is an error case.
Assuming there will always be one (and only one) character before the number, you can simply do this:
string numberAsString = "c2".Substring(1);
And to make that an int:
int number = Int32.Parse(numberAsString);
You can use Regex to replace all alpha characters eg
string result = Regex.Replace(myString, #"[a-zA-Z\s]+", string.Empty);
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);
I have an array:
class Words
{
public static string[] wordsArray = { "one", "two", "three", "four" };
}
TextBlock which displays an array of values, and button that displays the next value of the array:
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
if (counter < Words.wordsArray.Length)
{
enWordTextBlock.Text = Words.wordsArray[counter++];
}
}
When the box appears on the last value of the array, the program will continue to not work, how to make it work in a "circle"?
Thanks all!
This should work:
private void goButton_Click(object sender, RoutedEventArgs e)
{
counter++; //increase the counter
int i = counter % Words.wordsArray.Length; //modulo operation
enWordTextBlock.Text = Words.wordsArray[i]; //set text
}
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter++ % Words.wordsArray.Length];
}
[Edit]
Ok, this is an edit related to user1397396 comment. I'm not sure I understand you correctly, but you might have a problem with negative value modulus. For example:
int counter = 0;
int mod = 4;
counter--; // counter is -1 after this line is executed
int result = counter % mod; // result is -1
result = (counter + mod) % mod; // result is now 3 as desired
Here is how I would implement these Next and Previous buttons.
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter % Words.wordsArray.Length];
counter++; // put ++ operator in new line to avoid confusion
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
int wordCount = Words.wordsArray.Length;
// add wordCount before applying modulus (%) to avoid negative results
// -1 % 5 = -1; -2 % 5 = -2; -6 % 5 = -1 etc
// negative values would cause exception when accessing array
counter = ((counter - 1) + wordCount) % wordCount;
enWordTextBlock.Text = Words.wordsArray[counter];
}
For example, this code would cause pressing Next, Previous, Next to give you this: "one", "four", "one".
Even better solution would be to use a method (or to inline code) such as this:
private static int GetPositiveIntModulus(int value, int mod)
{
return ((value % mod) + mod) % mod;
}
It will give you a positive result for any value, even when value < -mod. So you could write the code above like this:
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
// uncomment this to ensure valid counter
// if it is changed somewhere else in the program
//counter = GetPositiveIntModulus(counter, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
counter = GetPositiveIntModulus(counter + 1, Words.wordsArray.Length);
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
counter = GetPositiveIntModulus(counter - 1, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
}