How to preserve dynamically created controls? - asp.net

I want to preserve the dynamically created control when postback occurs .
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateTable()
{
HtmlTableRow objHtmlTblRow = new HtmlTableRow();
HtmlTableCell objHtmlTableCell = new HtmlTableCell();
objHtmlTableCell.Controls.Add(new TextBox());
objHtmlTblRow.Cells.Add(objHtmlTableCell);
mytable.Rows.Add(objHtmlTblRow);
this.SaveControlState();
// this.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTable();
}
It can be achieved by calling CreateTable() in Page_Load. Is there any alternative way to preserve the control
Thanks

You can add them to a List when you create them and save your List to Session. On postback (Page_Load) load them from your Session to your Page.

the below code should work
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateTable()
}
public static Control GetPostBackControl(Page thisPage)
{
Control ctrlPostedback = null;
string ctrlName = thisPage.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
{
ctrlPostedback = thisPage.FindControl(ctrlName);
}
else
{
foreach (string Item in thisPage.Request.Form)
{
Control c = thisPage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
ctrlPostedback = c;
}
}
}
return ctrlPostedback;
}
The code works from UpdatePanel
Reference:http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page

Related

PageIndexChanging Event in search button in asp.net?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid();
}
}
protected void btnsearch_Click(object sender, EventArgs e)
{
objRetailPL.ZoneName = ddlzone.SelectedValue;
//IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
//String datetime = txtdate.Text.ToString();
//DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
//objRetailPL.date =dt;
DataTable dtsearch = new DataTable();
dtsearch = objRetailBAL.searchzone(objRetailPL);
GVRate.DataSource = dtsearch;
GVRate.DataBind();
}
protected void GVRate_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GVRate.PageIndex = e.NewPageIndex;
grid();
}
catch (Exception ex)
{
}
}
I have this code for searching records.And for that grid i added page index,but it is not coming properly.When click on search button it is showing more n of records at that time page index is not working. It is calling First grid before clicking search button..How can I change my code please help me.....
Try this ...
private void grid()
{
if(!string.IsNullOrEmpty(yourSearchTextBox.Text)
{
// Then call search method. Make sure you bind the Grid in that method.
}
else
{
// Normally Bind the Grid as you are already doing in this method.
}
}
you have to check whether there is any search Text or not in that grid() method like...

ASP.Net OnLoad Stop event handling

I have some validation code in my WebForm page. When a user clicks on a button and does a postback.
Page_Load event gets processed then the Button1_Click event gets processed.
I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.
Is a trick to do this?
Thanks
4 variations shown below.
public partial class _Default : System.Web.UI.Page
{
private bool MyPageIsValid { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bool valid = false; /* some routine here */
MyPageIsValid = valid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.MyPageIsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!this.MyPageIsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
I think it should be better to check validation conditions exactly in the Button1_Click method like this:
if (!this.IsValid()) { return; }
Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:
if (!this.isValid) { return; }

Why does DataPager need Pre-Render event to work??

Having to use pre render is causing me problems.. It would be great if I did not need it.. The problem is I have the list in a user control and when I goto the next 'page' I databind.. but then the datapager prerenders.. which also does a batabind.. so it runs twice..
If I remove the prerender .. then clicking next 'page' does nothing..
Any idea?
protected void Page_Load(object sender, EventArgs e)
{
GetSearchResults();
}
//protected void dpMembers_PreRender(object sender, EventArgs e)
//{
// GetSearchResults();
//}
public void GetSearchResults()
{
List<Person> listPerson = new List<Person>();
string strServer = "localhost";
string strAppPath = Server.MapPath("/");
PersonBusiness pb = new PersonBusiness(new PersonRepository());
listPerson = pb.GetAllPersons(strServer, strAppPath);
lvPersons.DataSource = listPerson;
lvPersons.DataBind();
}
Modify your Page load to
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GetSearchResults();
}
}
your prerender seems ok.

How to get all TextBox values from Repeater that contains UserControls?

I have one TextBox inside a UserControl, and this UserControl is repeating inside Repeater.
But, when user fills TextBox with values and after that I can't get values from TextBoxs.
default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
//filling repeater with dataset
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
On button1 click I'm trying to fill List<string> with values from textbox.texts
protected void Button1_Click(object sender, EventArgs e)
{
List<string> sss = new List<string>();
foreach (Control i in Repeater1.Controls)
{
foreach (Control item in i.Controls)
{
if (item is WebUserControl1)
sss.Add(((WebUserControl1)item).getString);
}
}
}
And UserControl code:
public string getString
{
get
{ return TextBox1.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
you should loop on all repeater's items and use FindControl to find your user control then call the getString method on such found instances, pseudo-code (not tested):
foreach(var rptItem in Repeater1.Items)
{
WebUserControl1 itemUserControl = ((WebUserControl1)rptItem .FindControl("WebUserControl1"))
if(itemUserControl != null)
{
var itemText = itemUserControl.getString();
}
}

How to do that fields not initialization?

how to do that every time s_Sort not update SortDirection.Desc
private SortDirection s_Sort = SortDirection.Desc;
protected void Page_Load(object sender, EventArgs e)
{
lblSort.Text = S_Sort.ToString();//every time == SortDirection.Desc - this is bad!
if (!IsPostBack)
{
ShowTree();
Validate();
}
}
Need
public void btnSortUp_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Asc;
}
public void btnSortDown_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Desc;
}
but after SortDirection.Desc is bad
The is a problem of the ASP.NET lifecycle. Every time a postback happens (for example, when btnSortUp or btnSortDown is clicked), a new instance of your page is created, i.e., S_Sort is reinitialized to Desc. If you want to persist the value between postbacks, you can store it in the viewstate, for example, by encapsulating it in a private property:
private SortDirection S_Sort {
get { return (SortDirection)(ViewState["S_Sort"] ?? SortDirection.Desc); }
set { ViewState["S_Sort"] = value; }
}

Resources