Search code examples
c#asp.netdropdownaspbutton

Pass variables (e.g. array) from one <asp:ListItem> to another one (cf.<asp:DropDownList>) after clicking on <asp:button>


Morning All

I have been wondering how to pass variables from one <asp:ListItem> (cf. asp:DropDownList) to another one after clicking on <asp:Button OnClick>, as the data is cleared owing to the auto-refresh. To illustrate my point:

On Page.aspx

<asp:DropDownList ID="test" runat="server" style="font-size:14px;text-align:center;border-radius:0; 
CssClass="ddl">                              
<asp:ListItem>&nbsp;&nbsp;&nbsp;&nbsp;checkfruit</asp:ListItem>
<asp:ListItem>;&nbsp;&nbsp;&nbsp;&nbsp;verify</asp:ListItem>
<asp:ListItem>bsp;&nbsp;testcheck</asp:ListItem>                           
 </asp:DropDownList>
<asp:Button OnClick="test_Click" return="false" ID="veg" Text="Submit" runat="server" style="margin- 
 left:30px; border-radius:0; width:90px;/>

On Code Behind.cs

```public double[] pte = new double[3]; //

protected void test_Click(object sender, EventArgs e)
{

string a = test.SelectedItem.Value;

switch(a)
{

case "verify":
double[] d = new double[3];
d = [8,2,1];
pte = d; 
break;

case "testcheck":
double c;
c = pte[0] + 1;
break;
}
}

The aim consists of passing values of p from verify to testcheck after clicking sequentially on those options, leading to c = 9 in testcheck. The matter is that p gets reinitialized to 0 when one switches from verify to testcheck owing to auto-refresh inherent to test_Click, and setting return="false" from the page.aspx has not improved this matter. Ideally I'd like to avoid duplicating codes by redefining d in testcheck. Thus, your feedback would indeed be appreciated.

Best,


Solution

  • To preserve the value set in pte from the PostBack, save it into the ViewState

    protected void test_Click(object sender, EventArgs e)
    {
        string a = test.SelectedItem.Value;
    
        switch (a)
        {
    
            case "verify":
                double[] d = new double[3] { 8, 2, 1 };
                //d = [8, 2, 1];
                pte = d;
                ViewState["pte"] = pte; // Save values
                break;
    
            case "testcheck":
                double c;
                pte = ViewState["pte"] as double[]; // Read values
                c = pte[0] + 1;
                break;
        }
    }