简体   繁体   中英

How do I return one item at a time with each button click?

I have an array that I declare above my form load:

protected string[] Colors = new string [3] {"red", "green", "orange"};

When I click this my submit I want to use a Response.Write(); to print out red for the first click, green the second time I click it, then finally orange the last time I click it. I was reading How do I get next item in array with each button click? and this user is trying to something very similar to what I am trying to do, however it looks as though the array in that case is dynamic.

Track it in a session

 protected void Page_Load(object sender, EventArgs e)
    {           
        int? count = Session["count"] as int?;
        count = (count == null) ? 0 : count;
        Response.Write(Colors[count.Value]);
        count = (count + 1) % Colors.Length;
        Session["count"] = count;
    }

You can use view state to keep track of some information through a request/response trail for a particular page. You can store an index in the view state and then use that information when the button is clicked to see what should be printed to the screen.

Still looking for a solution to this and whilst doing so saw this pop up This will get your button click amount:

ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;

As far as looping through the array I am still working on it. I have only been able to display the last item in the array.

You have to store the number of clicks in your ViewState and increase it by one in your button's click event handler.

private int NumberOfClicks
{
   get { return (int)(ViewState["NumberOfClicks"] ?? 0 );
   set { ViewState["NumberOfClicks"] = value; }
}


protected void btn_Click(object sender, EventArgs e)
{
   if(NumberOfClicks < colorArray.Length)
   {
           //write to response colorArray[NumberOfClicks];
           NumberOfClicks += 1;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM