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

I have the following line of code,
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName").ToString();
This returns the
System.NullReferenceException; Object reference not set to an instance
of an object.
I know why it is returning this exception and thats because there is nothing in that cell.
How do I correctly handle this?

try
if(sitesformdataset!=null&&sitesformdataset.Tables["Sites"]!=null)
{
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName").ToString();
}

You don't need to call .ToString()
.Field<string>("SiteName") convert to string , you don't need to call tostring again.
sitetb.Text = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName");
if your cell value null then you can't call ToString method of null object, that will fail.

If you have already checked for _selectedindex != -1 and being in the correct range the correct the code like this:
sitetb.Text = (sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName")?? "").ToString();
it is the short writing of this:
var cellContetnt = sitesformdataset.Tables["Sites"].Rows[_selectedindex].Field<string>("SiteName");
if(cellCount == null)
sitetb.Text = "";
else
sitetb.Text = cellContent.ToString();

Related

Check if an Object has something or not

I have the following property:
IDictionary<string, object> Values { get; }
The property has a few values having one of them the key "culture".
I tried to use that value and casting to a string:
String value = (String)data.Values["culture"] ?? defaultCulture;
This works when the item has some value but when it doesn't I get the error:
Unable to cast object of type 'System.Web.Mvc.UrlParameter' to type 'System.String'.
BTW, System.Web.Mvc.UrlParameter:
http://msdn.microsoft.com/en-us/library/system.web.mvc.urlparameter%28v=vs.108%29.aspx
In the debugger data.Values["culture"] has the value {}. I tested and:
var test_1 = data.Values["culture"] == null; // returns false
var test_2 = data.Values["culture"].ToString() == null; // returns false
How do I check if data.Values["culture"] has something in it or not?
Apparently, you are storing a UrlParameter in that dictionary entry. If you want to get a string out, you will need to use ToString().
The exact expression to use will depend on the type of defaultCulture. If it is a string, then
String value = data.Values["culture"] == null ? defaultCulture : data.Values["culture"].ToString();
if it is a UrlParameter, then
String value = (data.Values["culture"] ?? defaultCulture).ToString();
If you want to get the string if it indeed is a string and a default value otherwise, you can test the type of the valuer using as. Something like:
(data.Values["culture"] as string) ?? defaultCulture
Try this:
String value = (String) (data.Values["culture"] ?? defaultCulture);
The idea is to check for null before trying to cast.
did you use this?
string.IsNullOrWhiteSpace(somestring)

How can I convert a null value to string.empty before it has a chance to throw an exception?

I have the following code to enter a previous value into a DataGridView cell. If on row 0 and col 2 or greater, the val to the left, otherwise the value directly above:
private void dataGridViewPlatypi_CellEnter(object sender, DataGridViewCellEventArgs args)
{
// TODO: Fails if it sees nothing in the previous cell
string prevVal = string.Empty;
if (args.RowIndex > 0)
{
prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.ToString();
} else if (args.ColumnIndex > 1)
{
prevVal = dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex-1].Value.ToString();
}
dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal;
}
This works great as long as there is a value to be seen and copied over. If the cell is blank, though, I get:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
I'm guessing this is an opportunity to use the null coalesce operator, but (assuming my guess is good), just how do I implement that?
Try something like this:
string s = SomeStringExpressionWhichMightBeNull() ?? "" ;
Easy!
Assuming Value is what is null (not entirely clear from your post) you can do
object cellValue =
dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value;
prevValue = cellValue == null ? string.Empty : cellValue.ToString()
Use a method such as:
public static class MyExtensions
{
public static string SafeToString(this object obj)
{
return (obj ?? "").ToString();
}
}
then you can use it like:
object obj = null;
string str = obj.SafeToString();
or as an example from your code:
prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.SafeToString();
This creates an extension method, so if you add a using for the namespace that the extensions class is in all objects will appear to have a SafeToString method in intellisense. The method isn't actually an instance method, it just appears as one, so instead of generating a null reference exception if the object is null it simply passes null to the method, which treats all null values as empty strings.

is there a sort of isset() on .NET/C#?

I need to check if there is a param on the uri request.
So I need to check if that param is set. Is there a function on .NET/C#?
An unset value will be null or empty:
value = Request["param"];
if (String.IsNullOrEmpty(value))
{
// param is not set
}
If the param name is in the query string but the value is not, it will be empty. If the name is not in the query string, the value will be null. For example.
&param1=&param2=value
// Request["param1"] is String.Empty
// Request["param3"] is null
Yes, you can use HttpUtility.ParseQueryString() utility method which returns NameValueCollection and then cust call Get():
bool contains = HttpUtility.ParseQueryString(uri.Query)
.Get("ParameterName") != null;
Get() method
Returns A String that contains a comma-separated list of the values associated
with the specified key from the NameValueCollection, if found;
otherwise, null
EDIT:
If you have an instance of the HttpRequest then just use built in indexer like below:
bool contains = Request["ParamName"] != null;
In c# not implemented object is NULL. But if you try to acces to this object you will get the exception. You cat try to catch it or just add # before your variable.
So C# isset looks like this (for array of strings)
// Isset
internal static bool isset(String[] m, int index)
{
return (#m[index] == null) ? false : true;
}
Use it like this: if (App.isset(parts, 1)) cat = parts[1];
Or just "in plase" solution
if (#parts[1] != null) cat = parts[1];
I hope this ansver will help you.
You could use try and catch to wrap your uri request?
catch for NullReferenceException or just exception?

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

Object reference not set to an instance of an object

Getting this error on this code:
string pname = null;
pname = ag.FirstOrDefault().arrangement.parent.name;
when calling the line pname = ag.FirstOrDefault.....
The filed parent.name is empty(null), which is fine I want to get an empty(null) string in such case.
How can I get rid of the error?
Either ag is null, the FirstOrDefault call is returning null, arrangement is null, or parent is null.
Only you are in a position to determine which one of those is actually the culprit.
If the property ag.FirstOrDefault().arrangement.parent.name is null it means the object ag is null also. This is the reason you are getting object reference error.
The answer Leons provided is actually what I was going to suggest. You need to do some research on the problem its one of the simplest thing to avoid ( trying to reference a null object ) in programming.
You cannot access the properties of a null object. If ag.FirstOrDefault() will return null, then you will not be able to access arrangement.
var temp = ag.FirstOrDefault();
string pname = (temp!= null) ? temp.arrangement.parent.name : null;
You may need to do further null checking.
try
var obj = ag.FirstOrDefault();
if( obj !=null)
pname = obj.arrangement.parent.name ?? String.Empty;
or you can try
//This will set the variable to null:
var obj = ag.FirstOrDefault();
if( obj !=null)
pname = Convert.ToString(obj.arrangement.parent.name);
Note : ag.FirstOrDefault().arrangement.parent.name is nullable type

Categories