Null Reference Exception (object refrence not set) [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 9 years ago.
having null reference exception. its a update code i am passing values from combobox to a local variable and then pass it into method.
pro_business sb = new pro_business(); //business layer class
string name = up_name.Text;
sb.Ppro_name = name;
string type= type_combobox.SelectedItem.ToString(); //Having problem here!!)
string unit = unit_combobox.SelectedItem.ToString(); //Having problem here!!)
sb.Ppro_unit = unit;
string message1 = sb.UpdateProductDetails(name, type, unit);

The reason for the exception is that SelectedItem is null, e.g. if the user did not select an entry yet. If you are only interested in the text of the item, rather use the Text property. If you want to check that the user has made a selection, use the SelectedIndex property.
In order to solve this, this code should work:
if (type_combobox.SelectedIndex >= 0 && unit_combobox.SelectedItem >= 0)
{
pro_business sb = new pro_business(); //business layer class
string name = up_name.Text;
sb.Ppro_name = name;
string type= type_combobox.Text;
string unit = unit_combobox.Text;
sb.Ppro_unit = unit;
string message1 = sb.UpdateProductDetails(name, type, unit);
}
For details on NullReferenceException and on how to fix it, see this excellent post.

Related

Is there a cleaner way to set null fields to "N/A"? [duplicate]

This question already has answers here:
One liner for If string is not null or empty else
(6 answers)
Closed 5 years ago.
I have 5 plus elements in a view. Is there a cleaner way to check for nulls and set the values if they are before saving in my controller? For example:
string FN = viewModel.FirstName;
if (String.IsNullOrEmpty(FN))
{
FN = "N/A";
}
//copy and paste for lastname
//copy and paste for address
//etc
Create an extension method as such:
static class Helper
{
public static string NotApplicableIfNullOrEmpty(this string str) => String.IsNullOrEmpty(str) ? "N/A" : str;
}
then do something like:
string firstName = viewModel.FirstName.NotApplicableIfNullOrEmpty();
string lastName = viewModel.LastName.NotApplicableIfNullOrEmpty();
string address = viewModel.Address.NotApplicableIfNullOrEmpty();
First and simplest way is: using ternary operator
string fristName = String.IsNullOrEmpty(viewModel.FirstName) ? "N/A" : viewModel.FirstName;
Another option is using custom model binder:
ASP.NET Model Binder

Given an object with a property that is an array of objects, how does one set a specific instance of said property in C#? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have two objects: 'Table' and 'Record'. 'Table' has a property 'Items' that is an array of type 'Record[]'.
How do I set the 'Items' property of a specific instance of 'Table' (e.g., table.Items[0]) to a specific instance of 'Record' (e.g., first_record)?
I tried to code it as follows, but my code results in a "NullReferenceException was unhandled" error.
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items[0] = first_record;
table.Items[1] = second_record;
Thank you
Stackoverflow suggested a similar question that provided my answer. I failed to initialize the array. Here's the line I was missing:
table.Items = new Record[2];
Inserting that line into the code from my original question results in the following:
Record first_record = new Record();
first_record.Field1 = "r1f1";
first_record.Field2 = "r1f2";
first_record.Field3 = "r1f3";
Record second_record = new Record();
second_record.Field1 = "r2f1";
second_record.Field2 = "r2f2";
second_record.Field3 = "r2f3";
Table table = new Table();
table.Items = new Record[2];
table.Items[0] = first_record;
table.Items[1] = second_record;
That did the trick. Thank you Stackoverflow!

Adding elements to List<> doesn't work [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a List<> declared, which is accessable in the whole class
List<article> data;
Now I'm using a method to fill the List<>:
StreamReader sr = new StreamReader(filePath);
while (!sr.EndOfStream)
{
string[] Line = sr.ReadLine().Split(';');
article newArticle = new article();
newArticle.articleNumber = Line[0];
newArticle.description = Line[1];
newArticle.articleId = Line[2];
try
{
data.Add(newArticle);
}
catch(NullReferenceException ex)
{
// Nothing to do here
}
}
Each time, the loop repeats, the newArticle-Object contains all his elements, so it is definetely not null.
But it doesn't add to the data-List<>.
What am I missing?
In order to add items to the list, you must first initialise it.
Replace:
List<article> data;
with:
List<article> data = new List<article>();

NullReferenceException error C# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 9 years ago.
QueryClass Query;
string UserName = "";
int UserId = 0;
string email = txtEmail.Text;
string name = txtUserName.Text;
string phone = txtPhone.Text;
byte[] buffer = new byte[100];
UserName = Query.GetUserName(email); //returns a string value
if (UserName != null)
{
MessageBox.Show(UserName + " is already in the database");
}
if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
{
UserId = Query.GetUserId(email); //returns a int value
if (Query.AddNewImage(UserId, buffer) == true) //returns a bool value
{
MessageBox.Show("Done..!!");
}
}
MessageBox.Show("Error");
I'm getting the following error after I click the insert button (above code) of my program.
System.NullReferenceException
Message="Object reference not set to an instance of an object."
I'm getting that exception on following places. (i didn't check other places) code just stops these places and gives the error.
UserName = Query.GetUserName(email); //returns a string value
if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
Can anyone please help me to fix this error? I'm using Visual studio 2010.
You're using Query without actually setting it to anything. You likely need to construct an instance:
// Change: QueryClass Query;
QueryClass Query = new QueryClass();
Without creating an instance, when you call:
UserName = Query.GetUserName(email);
At this point, Query is still the default value (which is null for a reference type), and you'll get a NullReferenceException upon trying to use it.
On a side note, you might want to consider naming this variable query (lower case), and the class Query (or, better yet, a more descriptive name), in order to follow the normal .NET naming guidelines.

Using a variable inside a member of an object [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 8 years ago.
I am pulling several elements of data out of an object in C#. They are all in the same 'place' within the object, as in:
objectContainer.TableData.Street.ToString());
objectContainer.TableData.City.ToString());
objectContainer.TableData.State.ToString());
objectContainer.TableData.ZipCode.ToString());
I would LIKE to use a foreach loop to pull them all and be able to add more by adding to the array.
string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields)
{
objectContainer.TableData.{add}.ToString());
}
Can this be done, and if so, what is the correct procedure?
You would need to use reflection to achieve this:
var type = objectContainer.TableData.GetType();
foreach(var addressFieldName in addressFieldNames)
{
var property = type.GetProperty(addressFieldName);
if(property == null)
continue;
var value = property.GetValue(objectContainer.TableData, null);
var stringValue = string.Empty;
if(value != null)
stringValue = value.ToString();
}
Please note: This code is pretty defensive:
It will not crash if no property with the specified name exists.
It will not crash if the value of the property is null.
You can use Reflection to do this.
string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields)
{
var myVal = objectContainer.TableData.GetType().GetProperty(add).GetValue(objectContainer.TableData).ToString();
}
Note that this doesn't allow for array values that don't have a corresponding property on objectContainer.TableData.

Categories