Validation, Page events and ViewState - asp.net

i have two buttons on the page. One button is responsible for text fields validation that are to do with registration and the other with loging in. The problem was when i press one of the buttons it refreshes the page and shows all the invalid fields (i dont want the registration fields to be checked by the RequiredFieldValidator whent the user presses the login button).
so what i did i used the initialization event.. to prevent this from happening...
static bool oneButtonPressed;
protected void Page_Init(object sender, EventArgs e)
{
if (oneButtonPressed)
{
REgisterAge.Visible = false;
RegisterAge2.Enabled = false;
RegisterAge3.Enabled = false;
RegisterPassword.Enabled = false;
RegisterPassword2.Enabled = false;
RegisterEmail.Enabled = false;
RegisterEmail2.Enabled = false;
}
else
{
EntryPasswordRequiredFieldValidator10.Enabled = false;
EntryNameEntryRequiredFieldValidator9.Enabled = false;
}
}
protected void entry_Click(object sender, EventArgs e)
{
oneButtonPressed = true;
}
protected void submitButton_Click(object sender, EventArgs e)
{
oneButtonPressed = false;
}
}
The probelm here is that the bool is always false when the page is posted back and loads again.. i do remember my teacher saying i could either use a ViewState or a static variable/method to preserve my values. Am i being wrong here.. do i have to use the ViewState?

Why don't you assign a validationgroup to each of the fields + the relevant submit button.
Different validation groups will ensure that validation won't fire on the irrelevant form.
<asp:TextBox runat="server" ID="txtName" ValidationGroup="vRegistration"></asp:TextBox>
<asp:LinkButton runat="server" ID="btnSubmit" ValidationGroup="vRegistration"></asp:LinkButton>

Related

Validation in different Tabs of windows form using ErrorProviders

I am working on a windows Forms Application and trying to validate few textboxes using errorproviders but the problem is when I am clicking on a button present in Tab 1, all the textboxes even present on a different tabs gets validated. I want the validation to occur for textboxes present on the current tab and not on any control present on any other tab. How can I achieve this? Please help. Below is the code related to validation in the click event.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Enabled))
{
// Some Code here
}
}
Below is code used for validating and validated event for one textbox. I am using similar code for other textboxes as well present on other tabs.
private void txtFirstNm_Validating(object sender, CancelEventArgs e)
{
bool cancel = false;
if (txtFirstNm.Text.Trim().Length == 0)
{
cancel = true;
errorProvider1.SetError(txtFirstNm,"Please enter First Name");
}
else
{
cancel = false;
errorProvider1.SetError(txtFirstNm, "");
}
e.Cancel = cancel;
}
private void txtFirstNm_Validated(object sender, EventArgs e)
{
errorProvider1.SetError(txtFirstNm,"");
}
The Scenario that is given in my question can be handled by using below code. We can use the ValidationConstraint as Visible and this will make sure that Validation occurs on the Current visible Controls.
private void btnCreateUser_Click(object sender, EventArgs e)
{
if (this.ValidateChildren(ValidationConstraints.Visible))
{
// Some Code here
}
}

How to refresh a web page in asp.net

In my code i added dynamically some text-boxes and labels.
Then by dropdownlist event i want to refresh the page in a way that all the added text-boxes and labels will remove from aspx
how can it be done?
I assume you're using C#.
You can redirect to the current page by doing this from your code-behind:
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
Add AutoPostBack="True" for the DropDownList
Add an event to DropDownList for SelectedIndexChange
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
In the Code-Behind file :
private void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
Label1.Visible = false;
}
else
{
Label2.Visible = false;
}
}

Preserving user control on autopostback asp.net

I have two user controls: dsucTopLeft and dsucTopRight in an aspx page. Each of the user controls has a dropdownlist to select values from.
The aspx page has a button "Save".
In the OnClickEvent of the button, I take data from those user controls (which return the values from the drop down list). I need to insert these values into database. However, these values set to 0 after the button is clicked.
How would I preserve those values?
Code:
ParentTemplate.aspx
<div class="leftDashboard">
<uc:dsuc ID="dsucTopLeft" runat="server" />
</div>
<div id="rightDashboard">
<uc:dsuc ID="dsucTopRight" runat="server" />
</div>
It also has a button:
<asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save Dashboard" />
This is the codebehind for the button:
protected void SaveButton_Click(object sender, EventArgs e)
{
//If the mode is "CREATE", then it needs to insert the information about dashboard and the charts it contains
for (int i = 0; i < dsuc.Length; i++)
{
dsuc[i].dashboardId = dashboardId;
if (dsuc[i].chartId != 0) //Here, the chartId remains 0
dsuc[i].insert();
}
}
dsuc is an array. It is being populated in the following way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
}
UserControl:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
initializeDropDownList();//It initializes the drop down list
}
}
public void insert()
{
//It inserts into database
}
protected void chartDDLSelectedIndexChanged(object sender, EventArgs e)
{
oldChartId = chartId;
String chartTitle = chartDropDownList.SelectedItem.Text;
if (chartTitle != dropDownMessage)
{
chartId = int.Parse(chartDropDownList.SelectedItem.Value);
//Chart user control should be retrieved from the database and drawn.
chartTitleLabel.Text += "chart id : " + chartId.ToString() + " title: " + chartTitle;
//chartUserControl.Visible = true;
}
}
The user control i.e. the class of dsuc[] changes its chartId when an item in its drop down list is selected. I printed the value, it works. But that same value becomes 0 when the button in clicked.
Remove the if (!Page.IsPostBack)from
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
If not, it will only populate it when is not post back. As a click produces a post back, you'll want that code being executed :)
Also, it is probably that your clickp event is being called beforeselectedindexchanged`. In that case, the code that sets chartId is not executed (yet) when the click event is fired. You can solve that doing this:
public int ChartId { get { return int.Parse(chartDropDownList.SelectedItem.Value); }}
and calling that property instead. Also, you can use that property in your selectedindexchanged event handler

Handling events from dynamic controls NOT added on Page_Load?

I've read a few articles on here and the web that have informed me that I cannot simply add a new control dynamically to the page, wire it to a handler, and expect it to work.
The solution given each time is that the dynamic controls need to be added to the page on Init each time.
My problem is, my controls are NOT added to the page on init, they are added after ANOTHER postback.
the workflow is this:
Page Loads
User fills in a textbox, clicks a button
Page Posts back, creating dynamic link controls in the button_click event based on the input
User clicks one of those link controls to proceed to the next step.
so if this is the behavior I need to support, is there any way to do this? It has to happen in the button_click of step 2, because the dynamic controls are based on the input the user puts in step 2.
have I painted myself into a corner here? how else could I handle such a workflow?
After you dynamically create a link button, set a flag in your page's view state. On postback, re-create the link button if the flag is set in view state. Here's a demo:
Markup:
<asp:Button runat="server" ID="button1" OnClick="button_Click" Text="Create button A" CommandArgument="A" />
<asp:Button runat="server" ID="button2" OnClick="button_Click" Text="Create button B" CommandArgument="B" />
<asp:PlaceHolder runat="server" ID="placeHolder"></asp:PlaceHolder>
Code-behind:
public partial class Default : System.Web.UI.Page
{
private bool LinkButtonCreated
{
get { return ((bool?)this.ViewState["LinkButtonCreated"]).GetValueOrDefault(); }
set { this.ViewState["LinkButtonCreated"] = value; }
}
private string LinkButtonCommandArgument
{
get { return (string)this.ViewState["LinkButtonCommandArgument"]; }
set { this.ViewState["LinkButtonCommandArgument"] = value; }
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (this.LinkButtonCreated)
this.CreateLinkButton(this.LinkButtonCommandArgument);
}
protected void button_Click(object sender, EventArgs e)
{
if (!this.LinkButtonCreated)
{
string commandArgument = ((Button)sender).CommandArgument;
this.LinkButtonCreated = true;
this.LinkButtonCommandArgument = commandArgument;
this.CreateLinkButton(commandArgument);
}
}
private void CreateLinkButton(string commandArgument)
{
LinkButton linkButton =
new LinkButton
{
ID = "linkButton",
Text = "Click me",
CommandArgument = commandArgument,
};
linkButton.Click += this.linkButton_Click;
this.placeHolder.Controls.Add(linkButton);
}
private void linkButton_Click(object sender, EventArgs e)
{
LinkButton linkButton = (LinkButton)sender;
linkButton.Text = "I was clicked! Argument: " + linkButton.CommandArgument;
}
}

Viewstate null on postback

So I have a listbox on my page and some textfields. Through the textfields I can add an item to my listbox (click the button, it adds it to a private List which is then set as a ViewState and the list is databound again). My listbox is also in an updatepanel which gets triggered on the button's Click event. Problem: My Viewstate remains null on a postback so it gets reset each time.
Some code:
private const string VIEW_INGREDIENTS = "IngredientsList";
private const string VIEW_LANGUAGE = "CurrentLanguage";
private List<IngredientData> _ingredientsList;
protected void Page_PreInit(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (ViewState[VIEW_INGREDIENTS] != null)
{
_ingredientsList = (List<IngredientData>) ViewState[VIEW_INGREDIENTS];
}
}
else
{
// prepare ingredient lists
_ingredientsList = new List<IngredientData>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataTextField = "Text";
lstIngredients.DataValueField = "Name";
lstIngredients.DataBind();
}
protected void btnAddIngredient_Click(object sender, EventArgs e)
{
_ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });
ViewState[VIEW_INGREDIENTS] = _ingredientsList;
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataBind();
}
You're using vewstate during PreInit ? Try to check that a bit later during PreLoad.
Check if the page has EnableViewState="true":
<%# Page Language="C#" EnableViewState="true" ...
And verify the site-wide setting in web.config:
<pages enableViewState="true" enableViewStateMac="true" ... />
Now ASP.NET has built-in viewstate for list controls, so I wonder why you're writing custom code for it. The default viewstate should work well for what you're trying to accomplish.

Resources