tags:

views:

114

answers:

4

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.

+1  A: 

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.

Canavar
+1  A: 
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;
    }
}
Ahmy
you'd be setting the Session Cookie to 0 every call, which defeats the purpose. I am sure that is a mistake ;)
Chad Grant
I have update it and its working well with me
Ahmy
I'd store the value in ViewState instead of Session, in this case. And of course, @Deviant's point about the value reset is valid.
Cerebrus
A: 

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...)

Guffa
A: 

THANKS A LOT GUYS I DID IT !!!