I am trying to write the user login details to the Database.
When I click the submit button Im getting a NullReferenceException.
There are 4 TextBoxes
Username, Email, Password and ConfirmPassword.
protected void Button1_Click(object sender, EventArgs e)
{
if ((RegisterUserWizardStep.FindControl("Password") as TextBox).Text == (RegisterUserWizardStep.FindControl("ConfirmPassword") as TextBox).Text)
{
//call the method to execute insert to the database
ExecuteInsert((RegisterUserWizardStep.FindControl("UserName") as TextBox).Text,
(RegisterUserWizardStep.FindControl("Email") as TextBox).Text,
(RegisterUserWizardStep.FindControl("Password") as TextBox).Text);
Response.Write("Record was successfully added!");
ClearControls(Page);
}
else
{
Response.Write("Password did not match");
(RegisterUserWizardStep.FindControl("Password") as TextBox).Focus();
}
}
Thank you.
You mention there are four controls - Username, Email, Password and ConfirmPassword
The null exception you are seeing is almost certainly because FindControl(X) is returning null
A better way of checking is to do something like:
TextBox myTextBox = RegisterUserWizardStep.FindControl(X) as TextBox;
if(myTextBox != null){
//Continue
}
else{
//Write out some error information - now you know what the problem is.
}
Further, and this isn't related to your immediate error, but then you feed the contents of each of the text boxes directly into your ExecuteInsert method - you'd be better off doing some validation, too, just to check you have expected values.
Its likely that FindControl didn't find the control you are after, possibly because the TextBoxes are nested under another child control like a panel etc.
Instead of
if ((RegisterUserWizardStep.FindControl("Password") as TextBox).Text
try
TextBox passwordTextBox = RegisterUserWizardStep.FindControl("Password") as TextBox;
// .. same for username and email
if ((passwordTextBox != null) && (usernameTextBox != null) ... )
{
// Do something with the textboxes
}
// else you have a bug
This will also prevent you repeating the FindControl code on the same control (DRY principle)
In your description you've said that you have a Username TextBox.
The code is looking for RegisterUserWizardStep.FindControl("UserName").
Is this a typo in the question? otherwise it could be the cause of the exception.
Code like RegisterUserWizardStep.FindControl("UserName") as TextBox will return null either if there is no control named UserName or if the control named UserName can't be cast to a TextBox. This is most likely the source of your exception because you attempt to get the property Text of a reference that might be null.
To better understand where the problem is you can define an extension function:
static class ControlExtensions {
public T Find(this Control parent, String name) where T : Control {
var control = parent.FindControl(name);
if (control == null)
throw new ArgumentException(String.Format("Cannot find control named '{0}'.", name);
var t = control as T;
if (t == null)
throw new ArgumentException(String.Format("Control named '{0}' does not have type '{1}.", name, typeof(T).Name);
return t;
}
}
You can then get the Text property of the UserName control:
RegisterUserWizardStep.Find<TextBox>("UserName").Text
This call will throw a more descriptive exception if the control isn't found.
Related
There must be something I'm missing here. I have two instances of RadTreeView, for which I store node check data in a cookie. Upon page load, I then want to read this cookie, and set checked status accordingly.
So I have this OnDataBound event:
protected void RadTreeView1_OnDataBound(object sender, EventArgs e)
{
HttpCookie checkedCookie = Request.Cookies[DataType + "Checked"];
if (checkedCookie != null)
{
var cookieValue = checkedCookie.Values["Checked"];
if (cookieValue != null)
{
var checkedNodeValues = cookieValue.Split('*');
foreach (string nodeValue in checkedNodeValues)
{
RadTreeNode checkedNode = RadTreeView1.FindNodeByValue(HttpUtility.UrlDecode(nodeValue));
if (checkedNode != null)
checkedNode.Checked = true;
}
}
}
}
And in the foreach loop, I find a corresponding node for every cookie value. What's more is, their initial Checked status is false.
So why are all other nodes also getting checked?
Try using the RadPersistenceFramework. Adding a single entry for your treeview to the PersistenceManager (or PersistenceManagerProxy) control should let you store the checked state. You can see this here http://demos.telerik.com/aspnet-ajax/treeview/examples/applicationscenarios/persisting-treeview-settings/defaultcs.aspx?product=persistenceframework
Of course, storing the data depends a bit on your case (you can have a custom provider and still keep the data in a cookie, or you can keep things in a database, whatever works for you: http://demos.telerik.com/aspnet-ajax/persistence-framework/examples/custom-storage-provider/defaultcs.aspx).
I used the MSDN guide on creating Custom Extraction Rule, which presents this example (Extract method):
public override void Extract(object sender, ExtractionEventArgs e)
{
if (e.Response.HtmlDocument != null)
{
foreach (HtmlTag tag in e.Response.HtmlDocument.GetFilteredHtmlTags(new string[] { "input" }))
{
if (String.Equals(tag.GetAttributeValueAsString("name"), Name, StringComparison.InvariantCultureIgnoreCase))
{
string formFieldValue = tag.GetAttributeValueAsString("value");
if (formFieldValue == null)
{
formFieldValue = String.Empty;
}
// add the extracted value to the web performance test context
e.WebTest.Context.Add("someNameHere", formFieldValue);
e.Success = true;
return;
}
}
}
// If the extraction fails, set the error text that the user sees
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found: {0}", Name);
}
However, I just don't know how to use access the someNameHere in the Web Test and add it to the QueryString as a parameter.
Any help would be greatly appreciated.
Right-click on the request in the web test and select "Add URL query string parameter". Alter the name as needed and into the value field enter {{someNameHere}}. The doubled curly braces call for a context parameter value to be inserted. The doubled curly braces can be used to insert the value of a context parameter into many other places in a web test. Note that strings such as text{{someNameHere}}moretext can be used to join context values to other strings.
I have a Catcha value( Security Code ) that is store in Session on PageLoad and that is going to be used when user clicks the search button. If the User is IDLE for more than 20 Min the value of Session is get expired. And when user clicks on Search Button. It Throws error " Object Reference Not Set To an Instance of an Object".
On PageLoad:
if (!IsPostBack)
{
Session["CaptchaImageText"] = new RandomGen().GenerateRandomCode();
}
On SearchButtonClick event:
if (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString())
{
return true;
}
else
{
return false;
}
Here i get error "Object Reference Not Set To an Instance of an Object".
i have also checked wheather the Session["Captcha"]!= null. But still it shows the same error.
How to Redirect or show a message that "Session Timeout !Visit again" and close the Browser.
Thanks in Advance!
Your code looks like you're inconsistent with your Session variable naming (I'm a strong proponent of constants for these).
That being said, the easiest way to handle your situation is
private void Page_Load(object sender, System.EventArgs e)
{
Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));
if( string.IsNullOrEmpty(Session["Captcha"] as string) )
{
Server.Transfer("RedirectPage.aspx");
}
}
That will cause a page redirect on session expiration.
TO close the browser, you need a client-side script... there is no way to do it by server-side, so, you can generate some javascript calling window.close();. For th message error, check if the Session[] is not null, if you call some method of this and it's null, you will get this kind of exception. Try something like this:
if (Session["Captcha"] == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Session Timeout! Visit again.'); window.close();", true);
return false;
}
return (SecurityCodeTextBox.Text.Trim() == Session["Captcha"].ToString());
I have some problems with this code:
private void BoxVisibility(bool email, bool link, Control linkButton)
{
mainEmail.Visible = email;
foreach (Control c in PlaceHolder1.Controls)
{
c.Visible = false;
}
if (linkButton != null)
{
PlaceHolder1.Visible = true;
linkButton.Visible = link;
}
}
when I send to method Control all is ok, but when at first I put Control in Session['temp'] = Control, and then invoke the method like BoxVisibility(false, true, (Control) this.Session['temp']) in this case Control linkButton.Visible = link; doesn't take true, He's still remain false.
The "control" is a reference to a particular instance for this particular page.
The Page is recreated on every request, so a reference to an old instance of your control is no longer valid. So don't store controls in anything (Session, ViewState, static fields) that lives longer than the single request. Local (instance) fields of your page are safe.
Consider the following code:
public partial class TeacherControlPanel : System.Web.UI.Page
{
protected string username = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
username = (string)Request.QueryString["username"];
Ice_Web_Portal.BO.Teacher teacher = Ice_Web_Portal.BO.Teacher.GetTeacherByUsername(username);
if (teacher != null)
{
labUsername.Text = username;
labName.Text = teacher.TeacherName;
labTeacherCode.Text = teacher.TeacherCode;
Dept dept = teacher.Department;
if (dept != null)
{
labDepartment.Text = dept.DeptName;
}
}
else
{
//labErrorMessage.Text = "No teacher found";
}
}
protected void btnSendMail_Click(object sender, EventArgs e)
{
Response.Redirect(#"~/Teacher/TeacherComposeMail.aspx?username=mahabub" + username);
}
}
In this code, when I am declaring 'username' as private, it is initialized to null after subsequent post backs.
Why?
What is the secret?
Because ASP.NET is stateless meaning it does not keep it state from post back to postback. Save the user to the viewstate, session, or application to see it on postback to postback.
#region UserName
public string UserName
{
get
{
if (this.ViewState["UserName"] == null)
return string.Empty;
return (string)this.ViewState["UserName"];
}
set { this.ViewState["UserName"] = value; }
}
#endregion
Every time you do any postback, even for "simple" things like button click events, you're working with a new instance of the page class. That's ASP.Net 101.
Declaring the username field as private or protected has no bearing on this situation. The only bearing protected/private would have is the accessibility of the variable outside the class or in inherited members.
I believe this is likely a lifecycle problem.
When you navigate to this page for the first time, user name will only have a value if the query string was set for the request. So, "/TeacherControlPanel.aspx" will have a user name with no value, but "/TeacherControlPanel.aspx?username=SomeUserName". In these cases, the field username is only going to have a value if one is set. And if no querystring is set, then when the page processes the button click event, the load will fire, no query string set means that username will be null, which means that the click event will have nothing to append to the redirect string.
So the question is, in your application, what navigation path are you using to get to TeacherControlPanel.aspx?