C# - 从数据库中读取时,如何保持用户的控制值? [英] c# - How to maintain values in user control when read from database?
问题描述
我要保持视图状态的用户控制值
I want to maintain user control values in view state
我试过,但值将被删除
code:
在低于code口读取数据库中的值,并在用户控件加载它,它的工作,但如果我想添加一个多个用户控件时,单击Add按钮这些值将被删除
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);
}
}
}
}
下面code是用于添加用户控件时,单击Add按钮
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
任何想法?在此先感谢
推荐答案
的事实是,当你点击该按钮,页面做了回发,所以在里面的<$ Page_Load事件的code的一部分C $ C>如果(!的IsPostBack)不执行的条件。
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.
这包括创建 VisaUserControl
,你是动态创建。
This includes the creation of the VisaUserControl
, which you are creating dynamically.
这篇关于C# - 从数据库中读取时,如何保持用户的控制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!