how to handle null exception in C# - 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;}

Related

Excel IsError equivalent function in C#

Is there a function in c# that can help to check if the statement is going to return error.
I am aware about try{} catch{} but we can't use it in condition checking. For example:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = if(operationResult != null)
{
if(operationResult.Response != null)
{
operationResult.Response.ResponseText;
}
Else
{
"Null";
}
}
Else
{ "Null"; }
In the example above, I need to perform multiple checks to validate the operationResult object properties at multiple levels due to nested objects in it, to determine the final value I want to read and consume as server response value.
If we have some thing like IsError() function in Excel, we can simply try to read the final object property i.e. operationResult.Response.ResponseText; inside of that function and if any of the parent object is null and it has to throw an error it will return false and we can return the value from the else block as shown in the hypothetical example below:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = IsError(operationResult.Response.ResponseText)? "Null": operationResult.Response.ResponseText;
So, do we have something like this in C#? Hope this makes sense?
If you're using c# 6 or newer version then you can use null-conditional & null-coalescing-operator operator like below.
Here you need to place ? to check if object is null or not. If object is null then it will not perform any further check and return null. And null-coalescing-operator (??) will be used to check if value is null then it will return value provided afer ??.
string ServerResponse = SomeRestFunction.Trigger()?.Response?.ResponseText ?? "Null";

Check for null value in DataGrid View Field when Assigning Variable

I'm trying to assign a value to a string variable when making a change to a datagridview field. Unfortunately if it's blank, it crashes with a NullReferenceException even if I try to check if it's null. I also don't know of a more efficient way to write this.
string change = "";
if (dgGroups[cid, rid].Value.ToString() != null) //gets null reference exception if row/column is blank.
{
change = dgGroups[cid, rid].Value.ToString();
}
Your check should be like this. You are trying to call null.ToString() which is not valid and it will throw NullReferenceException .
string change = "";
if (dgGroups[cid, rid].Value != null)
{
change = dgGroups[cid, rid].Value.ToString();
}
If you are using C# 6.0 you can write
string change = dgGroups[cid, rid].Value?.ToString();//this will return null if Value is null
You can use the ?? operator:
change = (dgGroups[cid, rid].Value ?? defaultValue).ToString();

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.

converting object to string has error [duplicate]

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

FormatException: Input string was not in the correct format

I have Views field from one of my tables in the database. At first i allowed it to take nulls, and now it disallowed it to take null. The problem is that that exception is being thrown when i convert the SqlReader instance to an int..here is the code:
try
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr != null && dr.Read() && dr["Views"] != null && dr["PageNumber"] != null && dr["Replies"]!=null)
{
Name = dr["Name"].ToString();
ThreadName = dr["ThreadTitle"].ToString();
Views = int.Parse(dr["Views"].ToString());//it is being thrown here when i try to convert it to an int..How can i prevent that mistake from being thrown?
Replies = int.Parse(dr["Replies"].ToString());
Topic = dr["Theme"].ToString();
Subtopic = dr["Topics"].ToString();
PageNumber = int.Parse(dr["PageNumber"].ToString());
Time = (DateTime)dr["Time"];
}
dr.Close();
}
Try
View = dr["Views"] as int? ?? 0;
If the value in the db is null then above it's being cast into a nullable int which can accept nulls.
Use the coalesce operator ?? to set the value of View to some other value (in this case 0) if the value in the database IS null.
You can use int.TryParse() to avoid the error. If the probem is just the null, I would recommend to use System.Convert to handle these situations, because it's safer and clear:
View = System.Convert.ToInt32(dr["Views"]);
To avoid exception while convertion, use Int32.TryParse always.
How about
if(dr["Views"] != DBNull)
{
// do your parse here
}

Categories

Resources