How to correct my null exception? - c#

I have created a contact form using c# and web services. I would like to get an alert message if the user hasn't filled his name or when his name is a number. This is my C# code:
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Validation.WebService validate = new Validation.WebService();
bool ismail = validate.isEmail(TextBox2.Text);
if (!ismail)
{ Label1.Text = "your mail is wrong!!"; }
Validation.nameVal valid = new Validation.nameVal();
bool isname = valid.isName(TextBox1.Text);
if (!isname )
{ Label2.Text = "Your name is wrong!!"; }
else if (isname==null)
{ Label2.Text = "Please fill in your name"; }
if (isname && ismail)
{
{ Label1.Text = null; Label2.Text = null;
Label3.Text = "Your message has been send!";}
}
}
}
With this code, I have a null exception.

From your comment that the exception is on the line:
bool isname = valid.isName(TextBox1.Text);
then either valid or TextBox1 is null. Given that the line before is:
Validation.nameVal valid = new Validation.nameVal();
this points to it being the latter.
You need to check that TextBox1 isn't null before de-referencing it or make sure that it is initialised correctly.

Try changing the last bit of the code where you set Label1.Text and Label2.Text to null to:
Label1.Text = String.Empty; Label2.Text = String.Empty;

I am guessing that perhaps the validate is failing, or, possibly the setting of the label text to null is causing the issues. The code below should help
Validation.WebService validate = new Validation.WebService();
bool ismail = (!string.IsNullOrEmpty(Textbox2.Text)) && validate.isEmail(TextBox2.Text);
if (!ismail)
{
Label1.Text = "your mail is wrong!!";
}
Validation.nameVal valid = new Validation.nameVal();
bool isname = (!string.IsNullOrEmpty(Textbox1.Text)) && valid.isName(TextBox1.Text);
if (!isname)
{
Label2.Text = "Your name is wrong!!";
}
else if (string.IsNullOrEmpty(Textbox1.Text))
{
Label2.Text = "Please fill in your name";
}
if (isname && ismail)
{
{
Label1.Text = "";
Label2.Text = "";
Label3.Text = "Your message has been send!";
}
}
}

Related

Adding a new line when checking a checkbox

When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.

How can i store values of some text box in a item of a list box?? without a database., but by using array

we need to store the textbox.text in a single item in the index.if the selected index changes .the text in textbox should also change
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
tb[0].Text = textBox1.Text;
tb[1].Text = textBox2.Text;
tb[2].Text = textBox3.Text;
tb[3].Text = textBox4.Text;
tb[4].Text = textBox5.Text;
}
if (listBox1.SelectedIndex == 1)
{
t[0].Text = textBox1.Text;
t[1].Text = textBox2.Text;
t[2].Text = textBox3.Text;
t[3].Text = textBox4.Text;
t[4].Text = textBox5.Text;
}
You can do it using javascript easily.
call programTitleChange() javascript function on dropdown change event.
Javascript function :
function programTitleChange(elm) {
if (elm.options[elm.selectedIndex].text != "Select") {
document.getElementById('txtTitle').value =
elm.options[elm.selectedIndex].text;
document.getElementById('txtTitle').readOnly = true;
}
else {
document.getElementById('txtTitle').value = "";
document.getElementById('txtTitle').readOnly = false;
}
}

Trying to open a .ini file but i keep getting an error in C#

I'm new to coding so be nice. I'm trying to open a .ini file in a program, but I keep getting this error when I do so.
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
My code:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string reini = ini.Read ("Profile Settings", "User ID");
int i = int.Parse(reini);
textBox1.Text = i.ToString();
textBox3.Text = i.ToString();
textBox4.Text = i.ToString();
textBox5.Text = i.ToString();
string rechini = ini.Read("Startup", "Check");
if(rechini == "checked")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
}
}
}
Then the int i = int.parse(reini); gets marked in green
User ID is most probably an alphanumeric string. You'd be safer with .TryParse() in case user ID can be both of alphanumeric and integer types.
int i = -1;
string user_id = string.Empty;
if (!int.TryParse(reini, out i))
{
user_id = reini;
}
if (!String.IsNullOrEmpty(user_id)) // it is an alphanumeric
{
}
else // it is an integer, use i
{
}
UPDATE
Since your User ID is a string, just go with a string:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string user_id = ini.Read ("Profile Settings", "User ID");
textBox1.Text = user_id;
textBox3.Text = user_id;
textBox4.Text = user_id;
textBox5.Text = user_id;
string rechini = ini.Read("Startup", "Add To Startup");
if(rechini == "checked")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
}
}
}
UPDATE2
There is no Check key in your Startup INI file section. The code above is updated. There is Add To Startup, I guess you need this one.
As stribizhev said, in these cases, TryParse is better than Parse.
This is especially true as your User ID is a string of characters - not a number.
Also, 'Startup' 'checked' will always fail because the setting is named 'Add To Startup' (unless you will have another setting named 'checked' that is not in the file you supplied).
So, change to:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string reini = ini.Read("Profile Settings", "User ID");
textBox1.Text = reini;
textBox3.Text = reini;
textBox4.Text = reini;
textBox5.Text = reini;
string rechini = ini.Read("Startup", "Add To Startup");
checkBox1.Checked = rechini == "checked";
}
}

Error: "Input string was not in a correct format" on false statement

My code is working fine if the statement (numtickets > tickav) is true (if tickets available is greater than tickets ordered) But if other wise, it throws in this error "FormatException was unhandled by user code, Input string was not in a correct format" on int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
I do know that somehow I can use tryparse, i need help putting it in the code.
Any help would be appreciated, thank you
namespace TicketsApp
{
public partial class TicketOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["description"] != null && Session["EventID"] != null && Session["numtickets"] != null && Session["ticketcost"] != null
&& Session["State"] != null && Session["Section"] != null && Session["Row"] != null && Session["date"] != null)
{
if (!IsPostBack)
{
try
{
txtEventDescription.Text = Session["description"].ToString();
txtEventID.Text = Session["EventID"].ToString();
txtTicketsAvailable.Text = Session["numtickets"].ToString();
txtTicketCost.Text = Session["ticketcost"].ToString();
txtState.Text = Session["State"].ToString();
txtSectionNumber.Text = Session["Section"].ToString();
txtRowNumber.Text = Session["Row"].ToString();
txtNumberOfTickets.Focus();
lblOutput.Visible = false;
}
catch
{
lblError.Text = "Please Search for Tickets First!";
lblError.Visible = true;
btnOrderTickets.Visible = false;
Response.Redirect("TicketSearch.aspx");
return;
}
}
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int numTick = Convert.ToInt32(txtNumberOfTickets.Text);
string s = txtTotalCost.Text.Substring(1);
int totc = Convert.ToInt32(s);
int id = Convert.ToInt32(txtEventID.Text);
DateTime dt = Convert.ToDateTime(Session["date"]);
int returnedValue = NewOrder.PlaceOrderFull(id, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numTick, totc, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
protected void txtNumberOfTickets_TextChanged1(object sender, EventArgs e)
{
int cos = Convert.ToInt32(txtTicketCost.Text);
int numtickets = Convert.ToInt32(txtNumberOfTickets.Text);
int tickav = Convert.ToInt32(txtTicketsAvailable.Text);
if (numtickets > tickav)
{
lblError.Text = "Please Enter a valid ticket quantity";
lblError.Visible = true;
lblOutput.Text = "";
txtNumberOfTickets.Text = "";
}
else
{
int cost = cos * numtickets + 5;
txtTotalCost.Text = "$" + cost.ToString();
lblOutput.Visible = false;
lblFee.Text = "There is a $5 shipping fee";
lblFee.Visible = true;
lblError.Text = "";}
}
}
}
You can use int.TryParse which returns a boolean and does not throw an exception.
int numTick = 0;
bool result = int.TryParse(txtNumberOfTickets.Text, out numTick );
You can also do some client side validation to ensure that the field is filled in and contains a number.
Here is one of your methods rewritten using Int32.TryParse. I assumed you're doing txtTotalCost.Substring(1) to trim off the currency symbol. There are probably safe ways to do this, I'm just going to trim "$" for this example.
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
int numberOfTickets, ticketCost, eventId;
if(Int32.TryParse(txtNumberOfTickets.Text, out numberOfTickets) &&
Int32.TryParse(txtTotalCost.Text.TrimStart('$'), out ticketCost) &&
Int32.TryParse(txtEventID.Text, out eventId))
{
DateTime dt = Convert.ToDateTime(Session["date"]);
TicketsDataAccessDataContext NewOrder = new TicketsDataAccessDataContext();
int returnedValue = NewOrder.PlaceOrderFull(eventId, txtEventDescription.Text, dt, Session["State"].ToString(), Session["section"].ToString(), Session["Row"].ToString(), numberOfTickets, ticketCost, "vfateev");
if (returnedValue != 0)
{
lblOutput.Text = "Error has occured. Please try again";
lblOutput.Visible = true;
btnOrderTickets.Visible = false;
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Thank you";
btnOrderTickets.Visible = false;
}
}
else
{
lblOutput.Visible = true;
lblOutput.Text = "Some validation error message here...";
}
}
You will need to make similar modifications to txtNumberOfTickets_TextChanged1 to ensure the user has entered valid text.
simply use something like
To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll then
if (Information.IsNumeric(value))
{
DoSomthing();
}
else
{
DoSomethingElse();
}
UPDATE
OPEN VISUAL STUDIO ==> YOUR PROJECT
Click on solution and add reference, choose Microsoft.VisualBasic.dll confrim the new reference will be add to your references into the project.
Go at the top of your page and declare the import statemnet for Microsoft.VisualBasic.dll alias
using Microsoft.VisualBasic.dll;
then where you need to check the value of your textbox
if (Information.IsNumeric(yourtextbox.text.trim()))
{
//case true alias your value is numeric
//do what you need here like assing value to a var or any
//else
}
else
{
//put your logic here in case result is false and value
//is not numeric
}

If Statement true then Redirect

Hello im learning c# at the moment and wish to If a statement is true then redirect to another ASpage so far with no luck.
My attempt is below, what the code does is check the text boxes to see if they have a value and if they do then it will save that record in the database as a new user.The code works its just the redirect at the end that isn't working.
Any help would be great
protected void Button2_Click(object sender, EventArgs e)
{
if (!String.IsNullOrWhiteSpace(txtTitle.Text))
{
user.Title = txtTitle.Text;
}
if (!String.IsNullOrWhiteSpace(txtFirstName.Text))
{
user.Forename = txtFirstName.Text;
}
if (!String.IsNullOrWhiteSpace(txtSurname.Text))
{
user.Surname = txtSurname.Text;
}
if (!String.IsNullOrWhiteSpace(txtUsername.Text))
{
user.Username = txtUsername.Text;
}
// call save function at end of statements
if (!String.IsNullOrWhiteSpace(txtAddress.Text))
{
user.Address1 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtAddress2.Text))
{
user.Address2 = txtAddress.Text;
}
if (!String.IsNullOrWhiteSpace(txtPostcode.Text))
{
user.PostCode = txtPostcode.Text;
}
if (!String.IsNullOrWhiteSpace(txtCode.Text))
{
user.CountryCode = txtCode.Text;
}
if (!String.IsNullOrWhiteSpace(txtEmail.Text))
{
user.Email = txtEmail.Text;
}
//if (!string.IsNullOrWhiteSpace(txtDate.Text))
//{
// DateTime _entrydate;
// if (DateTime.TryParse(txtDate.Text, out _entrydate))
// {
// user.EntryDate = _entrydate;
// }
//}
user.CompanyID = AppSession.Company.ID;
user.Status = 1;
user.PasswordHash = "test";
user.EntryDate = DateTime.Now;
user.UpdateDate = DateTime.Now;
user.Deleted = false;
bool result = userDao.SaveNewUser(user);
if (result == true)
{
Response.Redirect("User/List/");
}
}
}
}
You need to Redirect to another ASPX page, not a directory.
Something like
Response.Redirect("User/List/UserList.aspx");
Private static string CheckValues(TextBox t)
{
if(!string.IsnullOrEmpty(t.Text.Trim())
{
return t.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
user.Title =CheckValues(txtTitle.Text);
user.Forename = CheckValues(txtFirstName.Text);
user.Surname = CheckValues(txtSurname.Text);
user.Username = CheckValues(txtUsername.Text);
user.Address1 = CheckValues(txtAddress.Text);
user.Address2 = CheckValues(txtAddress.Text);
user.PostCode = CheckValues(txtPostcode.Text);
user.CountryCode = CheckValues(txtCode.Text);
user.Email = CheckValues(txtEmail.Text);
if(CheckValues(txtDate.Text))
{
DateTime _entrydate;
if (DateTime.TryParse(txtDate.Text, out _entrydate))
{
user.EntryDate = _entrydate;
}
}
bool result = userDao.SaveNewUser(user);
if (result)
{
Response.Redirect("~/User/List/somepage"); //~ for root directory , if there is any page use that or use the exact url here.
}
}
Kindly note the above url format will only work if you have URL Rewriting/Routing in your app

Categories

Resources