CPK_2011 CPK_2011 - 3 months ago 25
C# Question

How to retain previous value for a textbox in onchange event in usercontrol

I have an user control with a few textboxes in it and how can I retain previous value of a textbox txtOne if a condition is not met in OnTextChanged event for the sum of txtA, txtB, txtC textboxes.

The variable "one" is considered as a previous value of the textbox. I have added the below code in usercontrol.

protected void txtOne_TextChanged(object sender, EventArgs e)
{
total = Convert.ToInt32(txtA.Text) + Convert.ToInt32(txtB.Text) + Convert.ToInt32(txtC.Text);
if (total > Convert.ToInt32(txtOne.Text.ToString()))
{
txtOne.Text = one.ToString();
}
}


Here "one" variable is getting value as 0. It should store previous value. Could you please give me a clue on where to store the value in "one" variable.

Answer

The code below is not in any way optimized or generalized. It is as close to your sample code as possible & designed to show you an answer based on your original code. I would suggest using comboboxes rather than textboxes, and/or using validation to make sure that the entries are all numeric. The code below doesn't go that far - it only answers your question based on the code you provided:

TextBox txtA = new TextBox();
    TextBox txtB = new TextBox();
    TextBox txtC = new TextBox();
    int total = 0;
    TextBox txtOne = new TextBox();
    string newOne = "";
    string someDefaultValue = "";
    string lastOne = "";
    protected void txtOne_TextChanged(object sender, EventArgs e)
    {
        total = getTotal(new string[] { txtA.Text, txtB.Text, txtC.Text });
        if (total > -1)
        {
            int totalTest = 0;
            if (int.TryParse(txtOne.Text, out totalTest))
            {
                if (total > totalTest)
                {
                    txtOne.Text = lastOne.Length > 0 ? lastOne : someDefaultValue;//default value for the first run when there is no last value 
                    lastOne = newOne;//whatever the value of "one" is this time
                }
            }
            else
            {
                MessageBox.Show("YOu must only enter numbers");
            }
        }

    }
    private int getTotal(string[] inputs)
    {
        int total = 0;
        int subTotal = 0;
        foreach(string input in inputs)
        {
            if(int.TryParse(input,out subTotal)){
                total += subTotal;
            }else{
                MessageBox.Show("You must only enter numbers");
                return -1;
            }
        }
        return total;
    }