Object reference not set to an instance of an object textBox - c#

Hello i need a help with my code here
Im really confused about this error, i want to pass the value from textBox1 (form 1) to textBox7 (form 2).
and it said NullReferenceException was unhandled
Form 1
private void button1_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = setIDtruk.getText;
this.Close();
}
catch(Exception)
{
MessageBox.Show("Wrong");
}
}
Form 2
public string getText
{
get
{
return textBox7.Text; // error in this statement
}
}
can anybody help me out ?
thanks

If you get a NullReferenceException on the line you indicate then the only reason that I can see is that testBox7 is null. We can't really tell you why it's null from the information that you've provided.

If it says NullReferenceException was unhandled it's probably because your TextBox7 is null.
You might need to go through your code and see where you missed a declaration.
If having a null TextBox is part of your code logic, in that case instead of returning the textBox7.Text directly, test it for null and if it is (null) return the appropriate value instead (like an empty string).

Related

C# skipping if not null

I have a click event handler which has to check if two text boxes are null or not, if both aren't the values are given to two variables and passed to another method.
One variable is a String, the other an integer. If the String is null but the integer isn't, it will work fine(Which it shouldn't!). But, if the integer is null and the String isn't, it will give me an error which is expected because it should not have reached that point.
Here's the code:
private void btnInsert_Click(object sender, EventArgs e)
{
String ActorName;
int Position;
if ((txtPosition.Text != null))
{
if ((txtActorName.Text != null))
{
ActorName = txtActorName.Text;
Position = int.Parse(txtPosition.Text);
InsertIntoArrayList(ActorName, Position);
PopulateActors();
}
else
{
MessageBox.Show("Please enter an Actor Name");
return;
}
}
else
{
MessageBox.Show("Please enter a position");
return;
}
}
As you can see, if txtPosition is not null, it then tests txtActorName. If either are null, it throws the relevant message. Assuming both are not null, it assigns the values to the variables and passes these to the InsertIntoArrayLIst method, followed by a call to the PopulateActors method.
If I enter an Actor name and a position, everything works fine. It's only if I don't enter a position that it somehow misses the fact that nothings entered, then slips up at the line Position = int.Parse(txtPosition.Text); because txtPosition is null.
Any help would be greatly appreciated!
Try using e.g. !string.IsNullOrEmpty(txtPosition.Text) instead of txtPosition.Text != null.
Alternatively, just use txtPosition.Text != "". After all, the Text property should never actually be null.
And of course, you should apply the same fix to both values, txtPosition and txtActor.
Don't confuse null and empty strings. They aren't the same thing.
The Text property of any control will only ever be null if you explicitly set it to null. In most cases you don't need to check this at all for that property; just comparing to an empty string is good enough
The String.IsNullOrEmpty() and String.IsNullOrWhitespace() methods are your friends.
There's no reason to nest the If blocks. Just use guard clauses to check one followed by the other for cleaner code:
.
private void btnInsert_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhitespace(txtPosition.Text))
{
MessageBox.Show("Please enter a position");
return;
}
if (string.IsNullOrWhitespace(txtActorName.Text))
{
MessageBox.Show("Please enter an Actor Name");
return;
}
int Position;
if (!int.TryParse(txtPosition.Text, out Position))
{
MessageBox.Show("Please enter a number in the position field");
return;
}
InsertIntoArrayList(txtActorName.Text, Position);
PopulateActors();
}
You could also use if (!string.IsNullOrWhiteSpace(txtPosition.Text) if you want to check for white spaces as well. Although performance wise it is a bit slower then using the standard string.IsNullOrEmtpy
if (txtPosition.Text != string.Empty) is another way to check.
Try This, it may resolve your Problem
ActorName = txtActorName.Text;
Position = int.Parse(txtPosition.Text=="" ? "0" : txtPosition.Text);

Resting a private variable that should not happen

I have a strange problem I'm checking in my code behind the user if he is active or not with as simple if .. in my Page_Load method as you can see here
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
this.getParameters();
if (!this.IsPostBack)
{
if (paramTR.ZevUser.Active == 0)
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
}
But when I make a go throw to this method I get allays nullreferenceexception why so ever .. but the private ZevUser variable is not null it's full..
I really don't have a clue why is this happing, it would be really cool if someone could explain me this why this is happening
Thanks for help and fast answer
You need to break your code down so you can debug it easier or add logging if you cannot debug this code locally.
Remember that when debugging something, the worse mistake you can make is to make assumptions. Start from the beginning and follow the process through. Don't assume that the problem is something and don't assume that the problem can't be something:
I've included a broken down, more readable version below. You can now add logging around this or easily add breakpoints:
private TimeReport paramTR;
private ZevUser zevUser;
protected void Page_Load(object sender, EventArgs e)
{
this.getParameters();
if (!this.IsPostBack)
{
if ((this.paramTR != null) &&
(this.paramTR.ZevUser != null) &&
(this.paramTR.ZevUser.Active == 0))
{
this.Response.Redirect("~/TimeReporting/TimeReportPanel.aspx");
}
this.bindData();
}
string sessionId = Session["SessionId"] as string;
if (sessionId != null)
{
int session = int32.Parse(sessionId);
ZevUser user = ZevUser.GetById(session);
if (user == null)
{
this.Response.Redirect("~/About.aspx");
}
}
}
Why are you passing the session id to ZevUser.GetById()? I would expect this to take a user id, or for the method to be called something like ZevUser.GetBySessionId(). At the moment it's quite confusing.
This line is causing the issue:
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
This is because Session["SessionId"] can be null, and is null in this case.
If you are looking to get the SessionId that is set by ASP.net, then use this.Session.SessionID (source).
If you are storing a value in Session["SessionId"] that you are trying to retrieve, then do a null-check first:
if (Session["SessionId"] != null) { ...
You should consider testing the SessionId variable before using it by doing something like that :
if (!string.IsNullOrEmpty(Session["SessionId"].ToString()))
ZevUser user = ZevUser.GetById(Int32.Parse(Session["SessionId"].ToString()));
The best way to debug your exception is to enable debug when the exception is thrown.
For this, go to Debug>>Exceptions
and then enable first four checkboxes (maybe) and then try debugging the project. You will be halted at the position from where the exception will be thrown.

MDIparent in Winform Application return Object reference not set to an instance of an object

I have a problem with this code. You can find all classes here.
If I launch the application and I want open a new Form i receive this error:
NullReferenceException : Object reference not set to an instance of an object.
The main application is set to isMDIcontainer = true;
Now I received the error in this part of code:
private void PluginClick(object sender, EventArgs e)
{
ToolStripMenuItem menu = (ToolStripMenuItem)sender;
Plugin.PluginForm form = ((PluginInfo)menu.Tag).CreateInstance();
form.MdiParent = this; // Here is thrown the error
form.Show();
}
Plugin.PluginForm is only an Extended Form. This is the CreateIstance() method:
public PluginForm CreateInstance()
{
if (!File.Exists(FileName))
return null;
Assembly ass = Assembly.LoadFile(FileName);
foreach (Type type in ass.GetTypes())
{
if (type.BaseType == typeof(PluginForm))
{
return (PluginForm)Activator.CreateInstance(type);
}
}
return null;
}
In the same sebsite someone says that this error could may be resolved in this way:
You must declare property system.window.form parentForm in interface
but I didn't understand how.
Chances are good that CreateInstance is returning a null because the FileName is wrong (incorrect filename or path).
The result of it returning a null is that the form variable is null and any member access on it (as in form.MdiParent will result in a NullReferenceException.
Make sure that the filename is correct and that the file exists in the path it is searched on.

objects are not null and exception is still raised

Answer: it was in the else code, but I thought there is no reason that code wouldn't point to that line.
Can someone offer an idea how it could be possible that I get "Object reference not set to an instance of an object" on this at Invoke method:
delegate void t(tabdescriptor tab);
internal void AddItem(tabdesciptor tab)
{
if (InvokeRequired)
{
t inv = new t(AddItem);
if (inv != null && tab!= null)
Invoke(inv, tab);
}
else
{
....
}
}
I'm not exactly sure what the actual issue is considering your example cannot be the code that executes, but please try something like this:
internal void AddItem(tabdesciptor tab)
{
if (InvokeRequired)
{
Invoke(new Action<tabdescriptor>(AddItem), tab);
}
else
{
//...
}
}
Also please make sure that it's not actually whatever is in the else part that fails.
If I remember correctly, this exception could be coming from inside the invoked method. If you place a try/catch inside the else of the AddItem method and a breakpoint inside the catch, do you catch the exception?
internal void AddItem(tabdesciptor tab)
{
if (InvokeRequired)
{
t inv = new t(AddItem);
if (inv != null && tab!= null)
Invoke(inv, tab);
}
else
{
try
{
....
}
catch
{
// breakpoint here
}
}
}
It's unclear whether it's a mistake in the given example, or not, but tab is never checked for null, yet it is passed as the argument.
Either it's probably null, or:
Also, inv is checked for null right after creating it (Good in C/C++, but unnecessary in C# as it throws an OutOfMemoryException upon failure), but it is done before checking o for null.

get and Set not working

I am writing the following get and set for validating an input from a Text Box. Basically it is supposed to check if the user has entered all of the values.
When I leave the TextBoxes empty , it does nothing and shows a '0' in output where that variable was being used. It does however show the system generated exception and stops the execution, but I wonder why doesn't it validate the input through the properties?
Here is my code:
public double RecoDoseSize
{
get
{
return recoDoseSize;
}
set
{
if (!(value>0))
{
MessageBox.Show("Please Enter the recommended dose size for this product");
textBox8.Focus();
}
recoDoseSize = value;
}
}
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
recoDoseSize = double.Parse(textBox8.Text);
NoOfDosespUnit = TotalContentProduct/recoDoseSize;
}
You are setting recoDoseSize, the backing field, not RecoDoseSize, the property which has your code in it. Thus, your code isn't executed. You need to change the second line of your method body to
RecoDoseSize = double.Parse(textBox8.Text);
(note the capital R).
Other have given the correct answer to the question as stated. Namely that you should call the uppercased RecoDoseSize if you want to use the getter/setter.
However it is extremely bad practice to show a message box inside the setter, because it violates the Principle of Least Surprise.
When someone looks at the line RecoDoseSize = double.Parse(textBox8.Text); it is not at all obvious that this operation could cause a message box to appear.
There are occasionally exceptions where it does make sense to have a setter trigger UI changes (for instance the Visible property on controls) however the default should always be to not do this unless you are sure it will be more confusing to not do so (for instance it would be surprising if you set Visible = false however it was still visible).
Regarding your comment on how you should implement it, the checking should be done in the click handler and the property can just be an auto-property, like so:
public double RecoDoseSize { get; set; }
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
double enteredSize;
if (!double.TryParse(textBox8.Text, out enteredSize) || enteredSize <= 0)
{
MessageBox.Show("Please Enter the recommended dose size for this product");
textBox8.Focus();
return;
}
RecoDoseSize = enteredSize;
NoOfDosespUnit = TotalContentProduct / recoDoseSize;
}
You'll want to use TryParse because with Parse you'll get an error if the text isn't a valid double. What TryParse does is return true or false depending on whether it succeeded, and it populates the out parameter with the result if it's successful.
So what this does is if it either failed to parse the result, or the result is <= 0 it shows the message box. In that case it also returns from the method so the rest of it isn't executed. Alternatively the rest of the method could be in an else block in which case the return isn't needed. It's a matter a style which way is preferred.
You're never actually using the getter/setter. You are using the actual field name: recoDoseSize directly. Change it to RecoDoseSize.
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
RecoDoseSize= double.Parse(textBox8.Text);
NoOfDosespUnit = TotalContentProduct/recoDoseSize;
}
You shouldn't be handling focus in your set statement.
Also, you need to make sure that value is not null, otherwise you can't compare it to anything (greater-than, etc.).

Categories