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.
Related
This question already has answers here:
How can I fix the error : "Unreachable Code Detected"
(4 answers)
Closed 3 years ago.
I want to check for empty string or null values for Subject Code and Subject Name so that empty string of subject code and subject name will not be store in the database. I'm new to c#. There is an error to the code. It stated cannot convert from bool to string. I tried so many ways but the error is still there. After fixing the error for converting from bool to string, it returned me an Not Found error. How should I change the return NotFound() error?
public IHttpActionResult PostAddSubjectCode([FromBody] ConfigSubjectCode SubjectCodes)
{
string Subject_Code = SubjectCodes.Subject_Code;
string Subject_Name = SubjectCodes.Subject_Name;
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name))
{
return NotFound();
}
else
{
string sql = "INSERT INTO[dbo].[GEO_SUBJECT_CODES] ([Subject_Code],[Subject_Name_BY_CLASS]) VALUES " +
"('" + Subject_Code + "', '" + Subject_Name + "');";
DBConnection dbConnection = new DBConnection();
dBConnection.UpdateTable(sql);
return Ok();
}
}
The error states exactly what the problem is: You're passing a boolean (Subject_Code == "" && Subject_Name == "") to String.IsNullOrEmpty which expects a string
You're setting empty string to the variables you're checking, making the if check pointless
Your SQL is open to injection
Strongly suggested: Getting started with ASP.NET MVC 5, it will also have links to newer Core examples.
I'll keep this here since we had a thread going and to point out the issues listed.
// These will make the if statement useless, it will never hit else
// string Subject_Code = "";
// string Subject_Name = "";
//Assumptions: Subject_Codes contians these props
if(string.IsNullOrEmtpy(SubjectCodes.Subject_Code) && string.IsNullOrEmpty(SubjectCodes.Subject_Name)){
// whatever you want to do...
} else {
//sql here - I'll skip the comments on why your sql is bad - re: use parameters
// return after successful sql - look into a try/catch
}
Look into DataAnnotations [Required] in your model instead - you gain both server and client side validation. I strongly suggest you go over extensive tutorials instead of piecemeal stuff.
Based on the above code what you have tried to do is compare boolean value to a string value which would give you an error try the solution below.
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name)){
return NotFound();
} else{
try{
//SQL Code
} catch (Exception ex){
//Your Code
}
}
Note: This is a quick fix for OP's problem, not the best practice.
Since your if/else both return, it will never get to the actual update code. And you were assigned both variable to a fixed empty string, which would never cause the if/else to work in any case. You want something like this:
public IHttpActionResult PostAddSubjectCode([FromBody] ConfigSubjectCode SubjectCodes)
{
string Subject_Code = SubjectCodes.Subject_Code; // these can't be fixed ""
string Subject_Name = SubjectCodes.Subject_Name; // these can't be fixed ""
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name))
{
return NotFound();
}
else
{
string sql = "INSERT INTO[dbo].[GEO_SUBJECT_CODES] ([Subject_Code],[Subject_Name_BY_CLASS]) VALUES " +
"('" + Subject_Code + "', '" + Subject_Name + "');";
DBConnection dBConnection = new DBConnection();
dBConnection.UpdateTable(sql);
return Ok();
}
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a SharePoint list that I'm reading. In this list there are a number of items that don't have a value assigned to them, throwing an error. The code I'm using is the following:
public class FacilitiesDal : BaseDal
{
public List<FacilitiesEntity> FetchItems(string siteName, string listUrl)
{
try
{
using (var site = new SPSite(siteName))
{
using (var web = site.OpenWeb())
{
PostEvent("Successfully opened: " + web.Url, BaseExceptionEventArgs.ExceptionLevel.Debug);
PostEvent("Attempting to load list: " + listUrl, BaseExceptionEventArgs.ExceptionLevel.Debug);
return (from SPListItem item in web.GetList(listUrl).Items
select LoadItems( item["Assigned To"].ToString() ?? "Unassigned",
item["Site(s)"].ToString(),
item["Job Category"].ToString(),
item["Status"].ToString(),
Convert.ToDateTime(item["Date required?"]),
item.ID.ToString(),
item.ContentType.Name,
item.DisplayName,
item.Name,
"",
item.Url,
item["Created By"].ToString(),
item["Modified By"].ToString(),
Convert.ToDateTime(item["Created"]),
item["Created By"].ToString(),
Convert.ToDateTime(item["Created"]),
item["Created By"].ToString())).ToList();
}
}
}
catch (Exception ex)
{
PostEvent("Error fetching Facility list items", BaseExceptionEventArgs.ExceptionLevel.Error, ex);
throw;
}
}
The following line being the problem:
select LoadItems( item["Assigned To"].ToString() ?? "Unassigned",
If I change that line to not try to read the assigned to field, like the following, it works fine:
select LoadItems( "Unassigned",
All I can deduce from this is that the null collase operator I'm using here to evaluate if the assigned to field is blank or not isn't working as I'm expecting it to, but I can't understand why. How am I meant to be thinking about this?
Regenerating issue,
string x = null;
String res = x .ToString() ?? "Unassigned"; // <= Will throw NullReference excep.
Console.WriteLine(res +" "+ x.ToString());
Reason for exception is NOT collase operator (??). But the use of ToString() with a null.
It can be confirmed with following example,
String x=null;
Console.WriteLine(x.ToString()); //<= Will throw NullReference excep.
Or more clearly here,
Console.WriteLine(null.ToString()); //<= Operator '.' cannot be applied to operand of type <null>
Hope this solved your confusion.
Furthermore here's how you can solve it :
String x="test";
Console.WriteLine((x ?? "notset").ToString()); // <= Will out test
String y=null;
Console.WriteLine((y ?? "notset").ToString()); // <= Will out notset
So your code :
select LoadItems( (item["Assigned To"] ?? "Unassigned").ToString() ....
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.
public TransImport()
{
ConnString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
conn_new = new SqlConnection(ConnString);
command_serial_new = conn_new.CreateCommand();
command_serial_new.CommandText = "SELECT 1 FROM YSL00 WHERE SERLNMBR = #slnr";
var p = new SqlParameter("#slnr", SqlDbType.NVarChar, 50);
command_serial_new.Parameters.Add(p);
//Here you will start reading flat file to get serialnumber.
//Here I have shown a simple call using one value 12345 but it will be 1000's of
//lines from flatfile.
if (CheckSerialNumber('12345'))
DisplayMessage("Good serialnumber"); //this function is not copied here.
}
private Boolean CheckSerialNumber(string SerialNumber)
{
command_serial_new.Parameters["#slnr"].Value = SerialNumber;
try
{
var itExists = (Int32)command_serial_new.ExecuteScalar() > 0;
if (itExists)
{
return true;
}
}
catch (Exception ex)
{
LogException(ex, "Error in CheckSerialNumber =>"+ command_serial_new.CommandText.ToString());
}
return false;
}
I get error in the above catch. It mentions
object reference not set to an instance of object
It is failing with the line that has ExecuteScalar.
I guess I am doing something wrong here, but unable to figure out so far.
Update 1: I have modified this question. Basically I created another question with an issue I am facing.. Also I have marked it as answered.
Here is the NEW question I have posted just now.
Getting timeout errors with SqlTransaction on same table
This happens if the ExecuteScalar() returns null. (eg, because no rows matched)
Since int is a value type, it cannot be null; therefore, you get an error.
Instead, you can cast it to int?, which is nullable.
#SLaks answer is correct.
Here is one more way to avoid the error. No need of null checking etc, Convert.ToInt32 takes care of everything.
var itExists = Convert.ToInt32(command_serial_new.ExecuteScalar()) > 0;
try:
int i;
object o = command_serial_new.ExecuteScalar();
if(o != null && Convert.ToInt32(o.ToString()) > 0)
{
//....
}
to verify that your query returned something
I'm having an issue for C# (I'm new to it), when trying to fix a Null value.
Therefore I have a variable "verif" (String verif = String.Empty;), which I used it to read some key from Windows Registry. My code works if the key exists, but when it doesn't I got the error"NullReferanceException was unhandled".
I tried several ways, to catch the exception, to put an "If" statement but I failed miserable.
My code is something like this:
RegistryKey key_user;
RegistryKey key_pwd;
String code = String.Empty;
String tara = String.Empty;
String tot = String.Empty;
String pwd_mdw = String.Empty;
String user_mdw = String.Empty;
String user_uca = String.Empty;
String pwd_uca = String.Empty;
String verif = String.Empty;
private void button1_Click(object sender, EventArgs e)
{tot = listBox1.SelectedValue.ToString();
//MessageBox.Show(tot);
tara = tot.Substring(tot.Length - 2, 2);
//MessageBox.Show(tara);
code = listBox1.SelectedValue.ToString().Substring(0, 2);
user_mdw = textBox1.Text;
//MessageBox.Show(user_mdw);
pwd_mdw = textBox2.Text;
//MessageBox.Show(pwd_mdw);
if (code == "CC")
{
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + tara + "_CC").ToString();
MessageBox.Show("Verif",verif);
MessageBox.Show(user_mdw, "user_mdw");
if (verif==null)
{
key_user = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_user.SetValue("user_mdw_" + tara + "_CC", user_mdw);
key_user.Close();
key_pwd = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_pwd.SetValue("pass_mdw_" + tara + "_CC", pwd_mdw);
key_pwd.Close();
MessageBox.Show("User and Password inserted successfully!");
textBox1.Clear();
textBox2.Clear();
}
else
{...
Any hints?
Many thanks in advance, Bogdan.
Looking at what you're trying to do, this line is most likely (one of) your problems;
verif = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
.GetValue("user_mdw_" + tara + "_CC").ToString();
If the key does not exist, OpenSubKey will return null, and you call GetValue() on it without checking.
You can change the line to add a check, something like;
var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials");
var value = key != null ? key.GetValue("user_mdw_" + tara + "_CC") : null;
verif = value != null ? value.ToString() : null;
if(verif == null) {
...
First of all you need to check
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials")
that this is not null. Then call the getvalue method. Beause if the above key is null then the following getvalue will throw exception.
Try the following check to test if Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") is not null else it will bomb:
if (code == "CC")
{
if (Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials") != null)
{
verif =
Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials").GetValue("user_mdw_" + "Test" + "_CC").
ToString();
}
Try checking for NULL on OpenSubKey() & GetValue() methods prior to using ToString() method.
You're trying to do too much in one line, without checking the results as you go.
First of all, as others have already said, you need to check that OpenSubKey doesn't return null. You also need to make sure that the key is closed when you're finished, with a using statement:
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\TDCredentials"))
{
if (key == null)
{
// Couldn't open the key, now what?
// You need to make a decision here.
// If you read the documentation for CreateSubKey,
// you'll see that it can *also* return null, so don't rely on it.
}
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values. See the next part of the answer.
}
}
If you successfully open the key, you can try to read the value. Even if you successfully open the key, the value might not exist, or it might not be a string (it could be a DWORD, for instance, or a binary value).
If the value doesn't exist, GetValue returns null, so calling ToString without checking will throw NullReferenceException.
Even if the value exists, calling ToString on it is the wrong thing to do, because it might not be a string value in the registry. If it's a binary value, for example, calling ToString on it will give you the string System.Byte[]. You need to check that it is actually a string.
else
{
// OK, opened the key, and the using statement will close it.
// Now we can try reading values.
string verif = key.GetValue("user_mdw_" + tara + "_CC") as string;
if (verif == null)
{
// The value does not exist, or is not the type you expected it to be (string).
// Now what? You need to make a decision here.
}
else
{
// OK, do something with verif.
}
}
Make sure to read the documentation for these methods, and handle the special cases they mention, especially the circumstances under which they return null:
CreateSubKey
OpenSubKey
GetValue