我想在视图状态下维护用户控件值
我试过了,但值被删除了
代码:
在下面的代码中,我从数据库中读取值并将其加载到用户控件中,它正在工作,但是如果我想在单击添加按钮时再添加一个用户控件,这些值将被删除
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);
}
在下图中,如果我单击 Add More Visa 按钮,这些值和控件将被删除,我想保留这些值
有任何想法吗?提前致谢