converting object to string has error [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
My code is this :
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT Name FROM Table WHERE (Blogger = #Blogger)", scn);
scm.Parameters.AddWithValue("#Blogger", lblBloger.Text);
scn.Open();
MyLabel.Text = scm.ExecuteScalar().ToString();
scn.Close();
in this line :
lblLastNo.Text = scm.ExecuteScalar().ToString();
Has this error :
Object reference not set to an instance of an object.
or when I using if statement , shows same error
object Blogger= "";
if (Blogger.ToString() != string.Empty)
{
....
}
in below code again shows same error .

Most likely scm.ExecuteScalar() is bringing you a null value. You need to test the value returned before using it:
var result = scm.ExecuteScalar();
MyLabel.Text = result == null ? '' : result.ToString();

scm.ExecuteScalar() is returning null, or scm is null, or lblLastNo is null. That's the only reason you get the error 'Object reference not set ..'.

ExecuteScalar return an Object type. This is why you have the same behavior on scm.ExecuteScalar().ToString(); or Blogger.ToString().
The object type default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.
If this object is NULL, you will receive the error Object reference not set to an instance of an object.
Your second case with :
object blogger= "";
if (blogger.ToString() != string.Empty)
{
....
}
Should not throw an Exception but return a string that represents the object instance. For example : "YourNameSpace.Blogger"

Please enclose with try catch block, so that you can handle runtime exceptions and its makes life easier to understand the problem. and for if (Blogger.ToString() != string.Empty) this u can check for Null condition or if its string. Then you can check for String.IsNullorEmpty
string str=blogger.toString();
if (String.IsNullOrEmpty(str))
//do something
else
//do other part
String Is Null or EMpty

Related

How to avoid Nullreference exception when searching in List [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I am trying to get a list item that contains a certain string and I am using this code:
string myListLine= myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("mystring "));
All works well but if the list does not contain a particular string it throws an error:
object reference not set to an instance of an object
I think that I should somehow validate if the string first exists but not sure what would be the best approach.
if the list does not contain a particular string it throws an error:
That is not correct. The exception is thrown, because you have a null value inside your list! If all of your items in the list are valid strings then there will be no exception thrown. In this case FirstOrDefault will simply return null.
I think that I should somehow validate if the string first exists
You can check whether it is null the oldscool way first and combine it with an logical AND && with the Contains method
string myListLine= myList.FirstOrDefault(stringToCheck =>
stringToCheck != null && stringToCheck.Contains("mystring "));
This way the second Contains will not be evaluated if the first condition evaluates to FALSE
You can use the safe navigation operator and the null-coalescing operator to fix this:
System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string> { null, "Test123" };
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck?.Contains("mystring ") ?? false);
The problem occurs if you're calling a method on a null list entry.
Note: If the list is empty FirstOrDefault returns null.
Hope that helps.
Your code simply goes through myList, for each item, it checks if it contains "mystring ".
Only reason you may get a null reference while running that line is your list myList is null. It wouldn't get any error if it is empty.
if you get a null reference after that line, that would mean that myListLine is null, which would mean myList did not contain any items that matched "mystring ".
To make sure you do not get a null reference error with myListLine you should check if it is null before accessing it by using something like this;
if( myListLine != null ){
<Do something to myListLine>
} else {
<list doesnt contain the correct string, alert user.>
}
I think this sample code of mine is one of the safest way by accessing the myList object. If it is null then return an indicator that value was not found or empty.
List<string> myList = new List<string>()
{
"name","adress","phoneNumber"
};
myList.RemoveAll(item => item == null);
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("myString")) ?? "Not found/Empty";
A variation:
var myList = new List<string>(){"foo","Bar", null,"the mystring"};
string myListLine = myList.FirstOrDefault(s => s == null? false : s.Contains("mystring"));
Same notes as already mentioned regarding FirstOrDefault being null if empty list or no match (does not Contains)

how to handle null exception in C#

im getting null exception . while im directly exceciting this page. i want to handle null exception
C#
string json = "";
if (Request.QueryString["data"] !="")
{
json = Request.QueryString["data"];
var req = JsonConvert.DeserializeObject<Request>(json);//getting error in this line
string requestid = req.requestId;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString);
SqlCommand cmd = new SqlCommand();
connection.Open();
}
error
Value cannot be null.
Parameter name: value
Well presumably Request.QueryString["data"] is null. You're currently checking whether it's a reference to an empty string, but not whether it's a null reference. I suspect you want to use string.IsNullOrEmpty to check that:
string json = Request.QueryString["data"];
if (!string.IsNullOrEmpty(json))
{
var req = JsonConvert.DeserializeObject<Request>(json);
...
}
You can follow following two approach:-
Approach 1:
if (Request.QueryString["data"] != null && Request.QueryString["data"].toString() != string.Empty)
{
.. Your Content Goes Here
}
Approach 2:
if (!string.IsNullOrEmpty(Request.QueryString["data"].toString()))
{
.. Your Content Goes Here
}
you can u string.isNullOrwhiteSpace() Method and it returns a bool ...true if the input is empty ...false if there is any characters
You are getting such error when Request.QueryString["data"] is null. so you should check for null before using this value. in c# null cannot directly converted to String. Better method is suggested by john skeet.
string json=Request.QueryString["data"];
if(string.IsNullOrEmpty(json)){//Do your code;}

How do you properly check an SQLiteDataReader for null values?

I am trying to read some rows from a table in an SQLite database. I have a try/catch around my reader code:
try {
using (SQLiteConnection dbCon = new SQLiteConnection("Data Source=" + dbPath)) {
dbCon.Open();
using (SQLiteCommand command = new SQLiteCommand(sqlcmd, dbCon)) {
using (SQLiteDataReader rdr = command.ExecuteReader()) {
while (rdr.Read()) {
}
catch(exception ex) { throw ex; }
Something like that.
My problem is that any way that I check the reader values, say like:
if (rdr[3].ToString() != "" && rdr[3] != null) {}
It will always pass that if and then still throw an exception of "The given key was not present in the dictionary."
I simply want to reliably check these values so that I can skip over one but without having to hit the catch every time.
Given the previous example of checking for null:
if (rdr[3].ToString() != "" || rdr[3] != null) {
int something = Convert.ToInt32(rdr[3]);
}
this will error everytime there is no value in that field, because it will also always pass the 2 checks in the if.
I once tried to check against the null-type, too. Actually, you have to check against the special type of DBNull:
if (rdr[3].GetType() != typeof(DBNull)) { }
Since the data reader returns the singleton instance DBNull.Value a null column's value will be of the type DBNull. We can leverage this fact by using the as operator to convert our value to a reference null if the column value is null
String varcharValue = rdr[3] as String;
So here we would either have an instance of string or a null reference if the column value is null.
Unfortunately, this technique will not work directly with value types. The following code will generate a compilation error:
int numberVlaue = rdr[1] as int; // Will not compile
However, we can use the nullible version of the type to accomplish a similar conversion:
int? nullibleNumberValue = rdr[1] as int?;
and the later check the HasValue property to see if the type is null.

Get Object Reference Error when trying to use Request.QueryString [duplicate]

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 page.aspx that reads the query string, and if the QueryString is something like page.aspx?id=1, it runs some code.
However, I want it to simply ignore that code if no QueryString is specified. If I simply go to page.aspx. Right now, the only code I have on page load is
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
That works if I go to page.aspx?id=1. However, simply going to page.aspx gives me this error:
object reference not set to an instance of an object
How can I load the page with no query string?
You need to check for nulls
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
You can do this:
if(Request.QueryString.Length != 0)
{
...
}
If you try to access elements which are not present, you'll receive an exception. So, since QueryString has a property of Length, checking it against 0 means there is no query string at all.
Else if you want to know that only if id key isn't present, you can do this:
if(Request.QueryString.AllKeys.Contains("id"))
{
}
Try this:
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
Another way :
string id = Request.QueryString["id"] ?? "";
if(id == "1")
{
//Do something
}
This will cover any null reference issues or when there simply is an empty query string
if (Request.QueryString != null && Request.QueryString["id"] != null && Request.QueryString["id"] == "1")
{
//do work
}
Whenever you see this error :
object reference not set to an instance of an object
Know that you are checking for something that is null or simply doesn't exist
so try this :
if(Request.QueryString["id"] != null)
{
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
}

Object reference not set to an instance of an object

When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error.
The piece of code I get this error :
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check
TextBox1.Text = XResult == null ? String.empty : XResult.ToString();
If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it.
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}
That error could be Because the REquest.QueryString method did not find a value for "res" in the url so when you try to do the "toString" to a null object whrow that exeption.
Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval. It's not present in the address supplied to the browser. In the web section of your project properties, you can supply an appropriate URL. Of course, shoring up your code to allow for this would be advisable.
XResult is already a string, so calling ToString isn't necessary. That should also fix your problem.
The problem here is that XResult is null, and when you call ToString
on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check:
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}

Categories

Resources