Cannot update form from Page_Load - c#

I have a form with a lot of textboxes, dropdown menus and so on.
I use this form for entering NEW data but I also want to use the same page to CHANGE data. But then I have to fill the data with the information of the customer to be changed.
Now in Page_Load I have
protected void Page_Load(object sender, EventArgs e)
{
Master.PageTitle(PageTitles.UpdateAdd);
NameValueCollection nvc = Request.Form;
if (nvc.Count == 2 && nvc["ThisIsAnUpdate"] == "1")
{
// Ladies and gentlemen, we have an update. Do the work.
ThisIsAnUpdate.Value = "1";
DetailedAddressEntity myCustomer = new RetreiveInformation().FetchDetailedInformation(nvc["ID"]);
SetupEdit(myCustomer);
}
}
Then in SetupEdit I do this:
protected void SetupEdit(DetailedAddressEntity dae)
{
FirstName.Text = dae.aFirstName;
LastName.Text = dae.aLastName;
SubscriberNumber.Text = dae.aSubscriberNumber;
... and so on...
}
FirstName, LastName and SubscriberNumber never changes. They work perfectly when I use the page to create a new Customer since then I do postback to fill these textboxes, but when I try to access them when the page loads ... nothing.
I know the code in SetupEdit is actually run, but after the page is already drawn in my browser. I tried to force a postback, but that didn't work either.
Helps?
More explanation: Page_Load first set's the title of the page through the main page, since I do this without trouble I assumed I would be able to fill the textboxes too.
DetailedAddressEntity myCusomter is just a gazillion variables fetched from the DB.
I use the fetched information to fill the textboxes, but - alas - no info in them.
More info:
I moved the database call to SetupEdit and created a button on the page and called that function just to see if the function was broken. It works perfectly. It fetches all the info and fills up my textboxes perfectly.
But not if I call the same from Page_Load.
protected void SetupEdit(string ID)
{
DetailedAddressEntity dae = new RetreiveInformation().FetchDetailedInformation(ID);
FirstName.Text = dae.aFirstName;
LastName.Text = dae.aLastName;
SubscriberNumber.Text = dae.aSubscriberNumber;
... and so on...

protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Master.PageTitle(PageTitles.UpdateAdd);
NameValueCollection nvc = Request.Form;
if (nvc.Count == 2 && nvc["ThisIsAnUpdate"] == "1")
{
// Ladies and gentlemen, we have an update. Do the work.
ThisIsAnUpdate.Value = "1";
DetailedAddressEntity myCustomer = new RetreiveInformation().FetchDetailedInformation(nvc["ID"]);
SetupEdit(myCustomer);
}
}
}

Related

Saving values from User Control

I have an aspx page. On pageLoad a call a method that loads a user control
protected void Page_Load(object sender, EventArgs e)
{
LoadUC();
}
This loads the user control onto the page (into a placeholder) passing a few generic values.
private void LoadUC()
{
ucTS ctrl = (ucTS)Page.LoadControl(_ucTSPath);
ctrl.ParentId = 0;
ctrl.addNew = false;
phFG.Controls.Add(ctrl);
}
The user control (which contains a repeater) loads the initial placeholder as well as another placeholder on the initial page:
protected void Page_Load(object sender, EventArgs e)
{
LoadItems();
}
private void LoadBOMItems()
{
List<Item> dtItem;
if (ParentId == 0)
{
if (ViewState["ItemFG"] == null)
{
dtItem = //Gets list of items
}
else
{
dtItem = (List<Item>)ViewState["ItemFG"];
}
ViewState["ItemFG"] = dtItem;
}
else
{
if (ViewState["Items" + ParentId] == null)
{
dtItem = //get list of items
}
else
{
dtItem = (List<Item>)ViewState["Items" + ParentId];
}
ViewState["Items" + ParentId] = dtItem;
}
if (dtItem.Count > 0)
rptTSItem.DataSource = dtItem;
rptTSItem.DataBind();
}
}
in the binding, I bind the repeater, but I am also adding more of the same user control.
The problem comes when I click add a new item to the repeater. The initial click, everything saves fine and a new row is added. The second click the user control is not found on the initial page and so the save method is not fires. The 3rd click, everything is fine, the 4th, the user control is not found. This keeps happening. Why is my usercontrol not always found? I have tried doing a postback check in multiple places, but that doesn't seem to work.
I am still not 100% sure why the event would fire properly every OTHER time as opposed to just the first time, but the solution was simply adding an ID to the user control.
private void LoadUC()
{
ucTS ctrl = (ucTS)Page.LoadControl(_ucTSPath);
ctrl.ParentId = 0;
ctrl.addNew = false;
ctrl.ID = "someID"
phFG.Controls.Add(ctrl);
}
and whenever I re-added the user control from within the user control, I pass the same ID.

managing and controlling the post back priority

I have a web page which is contained a Data Filter and a report.The Data Filter is a user control. The report is loaded inside the main page so totally i have two pages. one user control and one web page.
Now i am going to gather the data by clicking a button inside the user control then i can use it to filter the table, but it seems that during the post back it goes first to the Page_Load method of the main, not the user control so the report is constructed before filtering.The BtnPreviewReport_Click must be executed earlier than the page_Load.
What should i do ?
User control
protected void BtnPreviewReport_Click(object sender, EventArgs e)
{
Date = Year.Text + "/" + Month.Text + "/" + Day.Text;
}
Main Page
protected void Page_Load(object sender, EventArgs e)
{
string date = UserControls1.Date;
Response.Write(date);
}
Output : Nothing
I am not sure why the ButtonClick event should be run earlier than page load.
But here's a simple way to solve your question:
private bool isPageLoaded = false;
private bool isButtonClicked = false;
private void ButtonClick()
{
isButtonClicked = true;
doTheFirstThing();
if( isPageLoaded )
{
doTheSecondThing();
}
}
private void PageLoad()
{
isPageLoaded = true;
if( isButtonClicked )
{
doTheSecondThing();
}
// else let the button click handle the SecondThing()
}

How I can Recover sorted data in a Grid View using C#?

I have a GridView with a search textbox and a Search Button, Once I try to search some records by Location, by Name, etc. I have a list of records that shows properly, if I select one record and I decide that is not the one I have and I click a back button that I include , my search is lost and I have to search again.
I understand that I have to create a session to solve this, but I am getting lost. This is what I have so far. Any idea?
protected void search_button_Click(object sender, ImageClickEventArgs e)
{
gvCompanyList.PageIndex = 0;
SearchForCompanies();
//Save search criteria into a session
Session["SearchString"] = tbSearchTerm.Text;
}
protected void gvCompanyList_PreRender(object sender, EventArgs e)
{
GridViewRow pagerRow = (GridViewRow)gvCompanyList.BottomPagerRow;
if (pagerRow != null && pagerRow.Visible == false)
pagerRow.Visible = true;
// To Call the session
String searchCriteria;
if (String.IsNullOrEmpty(tbSearchTerm.Text))
{
if (!String.IsNullOrEmpty(Session["SearchString"].ToString()))
{
searchCriteria = Session["SearchString"].ToString();
}
}
It looks as though you are on the right track. You just need to create a button now to execute the search using your session variable if it is clicked.

Creating, Using and Discarding Temporary Value not working

I am trying to assign a ViewState value in my application with a SelectedIndexChanged function. Once it's assigned the postback will use the value to change some data and then set the value to zero but I can't seem to get it to work correctly. The controls are all created dynamically on Page_Load.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
CreateAttributeControls();
TempProductVariantId = 0;
}
Create Attribute Controls
public void CreateAttributeControls()
{
...
var ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
ddlArtistArtworks.AutoPostBack = true;
...
}
ArtistArtwork_SelectedIndexChange
protected void ArtistArtwork_SelectedIndexChange(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
TempProductVariantId = int.Parse(ddl.SelectedValue);
}
TempProductVariantId ViewState Save
public int TempProductVariantId
{
get
{
if (ViewState["TempProductVariantId"] == null)
return 0;
else
return (int)ViewState["TempProductVariantId"];
}
set
{
ViewState["TempProductVariantId"] = value;
}
}
When I load the page everything is fine. I change the DropDownList's value, It posts back, and the value is not set. Change it again the value is set and continues to change as I change the value of the DropDownList.
Any guidance on this would be greatly appreciated.
Note: I have tried changing when CreateAttributeControls() is called. In OnPreRender for example. I was given this to understand the lifecycle of the page Life Cycle
That's because you are essentially recreating the dropdown on every postback..
try this
public void CreateAttributeControls()
{
...
DropDownList ddlArtistArtworks;
if (!IsPostBack)
{
ddlArtistArtworks = new DropDownList();
ddlArtistArtworks.ID = "ddlArtistArtworksTest";
divAttribute.Controls.Add(ddlArtistArtworks);
ddlArtistArtworks.Items.Clear();
ddlArtistArtworks.AutoPostBack = true;
}
else
{
ddlArtistArtworks = (DropDownLise)divAttribute.FindControl("ddlArtistArtworksTest");
}
ddlArtistArtworks.SelectedIndexChanged += new EventHandler(ArtistArtwork_SelectedIndexChange);
...
}
For dynamically added controls, the event handler has to be linked up everytime so that has to be done outside the if-block, unconditionally.

How can I load the Same ASP Grid View with different conditions?

I have a DDL and a ASP .net Grid view in my aspx page. I have two methods getALLProgram and getProgramBy name, both are working fine. My problem is: when the page is loaded for the first time, I want to call the getAllprogram method, after that if a User selects a program from DDL I want my getprogramByname method to be called.
How here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindProgramDDL();
BindGrid();
}
//BindProgramDDL();
}
protected void BindGrid()
{
string strProgramCode = DDLProgram.SelectedIndex.ToString();
List<FormGridEntity> gridEntities = new List<FormGridEntity>();
GridForResult.DataSource = gridEntities;
GridForResult.DataBind();
//throw new NotImplementedException();
}
protected void BindProgramDDL()
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
The Code is incomplete. i am still working on it. But I not getting the logic How will I make this happen that I have told you here. I hope I made my question clearly, if it confusing, please let me know what else I should provide here.
You should check in your BindGrid if any program has been selected or not and route the call as per that. For example,
protected void BindGrid()
{
...
if (DDLProgram.SelectedIndex >= 0)
{
// program selected
var programCode = DDLProgram.SelectedValue;
data = GetProgramByName(programCode);
}
else
{
// get all programs
data = GetAllPrograms();
}
// bind data with grid
}
You can either call BindGrid in page_load unconditionally (i.e. in post-back scenarios also) or invoke it on your DDL change.
how about writing getProgramByname on a selected index changed event of a drop down list and getALLProgram on page load event ?
I hope, I was clear on what your doubt and the above mentioned suggestion did helped.
Just change these 2 things
protected void BindGrid()
{
List<FormGridEntity> gridEntities = (DDLProgram.SelectedIndex==-1)
?FormSaleSubmit_BAO.GetAllPrograms()
:FormSaleSubmit_BAO.GetProgramByName(DDLProgram.SelectedValue);
GridForResult.DataSource = gridEntities;
GridForResult.DataBind();
}
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
BindGrid();
}

Categories

Resources