Question

I want to maintain user control values in view state

I tried but values are removed

Code:

In the below code I read the values from database and load it in user controls,it's working but if I want to add one more user control when click add button those values are removed

 protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
using (OleDbCommand cmd = new OleDbCommand("Select * from visa_details where emp_id = '" + empid + "'", DbConnection))
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{

  OleDbDataReader DR1 = cmd.ExecuteReader();
  while (DR1.Read())
  {
    string visaNumb = DR1[2].ToString();
    string visaCountry = DR1[3].ToString();
    string visaType = DR1[4].ToString();
    string visaEntry = DR1[5].ToString();
    string expiryDate = DR1[6].ToString();
    expiryDate =  DateTime.Parse(expiryDate).ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);

    VisaUserControl userconrol = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
    userconrol.TextVisaNumber = visaNumb;
    userconrol.VisaCountry = visaCountry;
    userconrol.VisaType = visaType;
    userconrol.VisaEntry = visaEntry;
    userconrol.ExpiryDate = expiryDate;
    rpt1.Controls.Add(userconrol);
   }
  }
 }
}

Below code is for adding user control when click add button

    public List<string> NoOfControls
    {
        get
        {
            return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];

        }
        set
        {
            ViewState["NoOfControls"] = value;
        }

    }


    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);

        GenerateControls();
    }



    private void GenerateControls()
    {
        foreach (string i in NoOfControls)
        {
            VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");

            ctrl.ID = i;
            this.rpt1.Controls.Add(ctrl);
        }
    }

    protected void btnAddVisa_Click(object sender, EventArgs e)
    {

        List<string> temp = null;
        var uc = (VisaUserControl)this.LoadControl(@"VisaUserControl.ascx");

        string id = Guid.NewGuid().ToString();
        uc.ID = id;

        temp = NoOfControls;
        temp.Add(id);
        NoOfControls = temp;
        rpt1.Controls.Add(uc);
    }

In the below image if I click Add More Visa button those values and controls are removed I want to persist those values

enter image description here

Any ideas? Thanks in advance

Was it helpful?

Solution

The fact is that when you click the button, the page does a postback, therefore the part of your code in the Page_Load event inside the if (!IsPostBack) condition is not executed.

This includes the creation of the VisaUserControl, which you are creating dynamically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top