Reputation:
I have a string[] arr. I want to make it like if I click the button once arr[0] goes to the textbox and If I click button again arr[1] goes to textbox.
I know it will be done using some counter and incrementing it on each click but im just confused with syntax. Help will be appreciated.
Upvotes: 1
Views: 4678
Reputation: 700680
There's a one-liner for everything. ;)
int _counter = 0;
string[] _values = {"1", "2", "3", "4"};
private void buttonClick(Object sender, EventArgs e)> {
TheLittleTextbox.Text = _values[_counter++ % _values.Length];
}
(Note: As the counter is not reset, it will overflow after 2 billion clicks... However, as you would have worn out a big pile of mice (clicking frantically day and night for about 20 years) to get there, I consider it safe enough...)
Upvotes: 0
Reputation: 5490
if(Session["Counter"] == null)
Session["Counter"] = 0;
string[] arr = new string[4] {"A", "B", "C", "D"};
private void button1_Click(Object sender, EventArgs e)
{
textbox1.Text = arr[int.parse(Session["Counter"])];
Session["Counter"]=int.parse(Session["Counter"])+1;
if (int.parse(Session["Counter"]) == arr.Length)
{
Session["Counter"]= 0;
}
}
Upvotes: 1
Reputation: 48088
Here is a sample :
int _Counter = 0;
string[] arr = new string[4] {"1", "2", "3", "4"};
private void buttonClick(Object sender, EventArgs e)
{
textbox.Text = arr[_Counter];
_Counter++;
if (_Counter == arr.Length) {_Counter = 0;}
}
If you're using this in ASP.NET application you should store _Counter in ViewState, Session or Cookie.
Upvotes: 2