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

后端 未结 4 1008
南笙
南笙 2021-01-19 17:23

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

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

When I clic

相关标签:
4条回答
  • 2021-01-19 17:38

    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;
        }
    
    0 讨论(0)
  • 2021-01-19 17:46

    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.

    0 讨论(0)
  • 2021-01-19 17:46

    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.

    0 讨论(0)
  • 2021-01-19 17:53

    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;
       }
    }
    
    0 讨论(0)
提交回复
热议问题