c# - 从数据库中读取时如何维护用户控件中的值?

时间:2013-10-01 06:58:18

标签: c# asp.net user-controls viewstate

我想在视图状态

中维护用户控件值

我尝试了,但删除了值

代码:

在下面的代码中,我从数据库读取值并将其加载到用户控件中,它正在工作,但如果我想在单击“添加”按钮时再添加一个用户控件,则会删除这些值

 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);
   }
  }
 }
}

以下代码用于在单击添加按钮

时添加用户控件
    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);
    }

在下图中,如果我单击“添加更多签证”按钮,则会删除这些值和控件,我希望保留这些值

enter image description here

有什么想法吗?提前致谢

1 个答案:

答案 0 :(得分:0)

事实是,当您单击按钮时,页面会进行回发,因此不会执行if (!IsPostBack)条件内的Page_Load事件中的部分代码。

这包括创建动态创建的VisaUserControl