Reputation: 147
I am getting nullrefernce exception after running c# code at this line
var data = info.details.Split('|');
c# code:
public studentinfo SaveData(studentinfo info)
{
bool returnBool=false;
SqlConnection con;
var data = info.details.Split('|');
var response = new studentinfo
{
ID = data[0],
Name = data[1],
Project = data[2],
Result = data[3]
};
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Myproject.Properties.Settings.MyConnection"].ConnectionString);
string sqlStr = "INSERT INTO Result (ID,Name,Project,Result) values('" + data[0] + "', '" + data[1] + "', '" + data[2] + "', '" + data[3] + "')";
SqlCommand dbCommand = new SqlCommand(sqlStr, con);
try
{
con.Open();
if (dbCommand.ExecuteNonQuery() != 0)
{
returnBool = true;
}
if (!data.Equals(null))
{
returnBool = true;
}
con.Close();
}
catch
{
returnBool= false;
}
con.Close();
return response;
}
I tried to implement:
if (!data.Equals(null))
{
returnBool = true;
}
but even then its giving the same object reference exception, Please help me to resolve it. Thanks
Upvotes: 0
Views: 18448
Reputation: 27
using C# last version
if(data is not null)
{
}
Note that
"== null"
and "!= null"
doesn't work for null reference
Upvotes: -1
Reputation: 3819
You need to check for null before you try the string split
if (info == null)
{
// do not attempt to split details, maybe throw something here
}
However, you may want to look at how that SaveData(studentinfo info)
is being called, and under what circumstances would it be passed a null studentinfo
object.
Upvotes: 0
Reputation: 73442
Try this
if(data != null)
{
}
Or
if(object.ReferenceEquals(data,null))
{
}
Probably as @zigdawgydawg pointed out exception will not be in checking data
because string.Split
will never return null
. So, you need to avoid null parameter.
if(info==null || info.details == null)
{
return null;//Or throw new ArgumentException();
}
Upvotes: 9
Reputation: 2046
The Null reference exception is because either info
or info.details
is null. You'll need to check for nulls before you do a Split
.
Upvotes: 2