I have this statement:
if (sqlClass.Reader != null && sqlClass.Reader.HasRows)
{
do
{
data = sqlClass.Reader.GetString(0); //error line System.InvalidOperationException {"Invalid attempt to read when no data is present."}
} while (sqlClass.Reader.Read());
}
the object sqlClass.Reader is of type System.Data.SqlClient.SqlDataReader
In C# it gives me an InvalidOperationException but in VB it worked fine, what would the reason be and how do I solve this?
Something like this:
if (null != sqlClass.Reader)
{
while (sqlClass.Reader.Read())
{
data = sqlClass.Reader.GetString(0);
}
}
Related
Using MySqlDataReader, I try to read a primary key which is int(11). int id=reader.GetInt32(0); gives the error "Object must implement IConvertible". What is the reason? How can I fix it?
reader.GetInt32(0) will accept the argument as columnIndex this will throw exceptions as like the following :credits to MSDN
you can trace out the error using :
while (reader.Read())
{
if (reader.IsDBNull(2))
{
Console.Write("<NULL>");
}
else
{
try
{
Console.Write(reader.GetInt32(2));
}
catch (InvalidCastException)
{
Console.Write("Invalid data type.");
}
}
Console.WriteLine();
}
I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a NullReferenceException in .NET?
Object reference not set to an instance of an object.
protected void Page_Load(object sender, EventArgs e)
{
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
try
{
if (Role != 3)
{
gv_ViewApplicants.Visible = true;
gv_ViewApplicants_SelectedIndexChanged(this, new EventArgs());
}
else
{
gv_ViewApplicants.Visible = false;
}
}
catch (NullReferenceException e1)
{
}
}
Try
int Role = Convert.ToInt32(Request.QueryString["Role"] != null ?
Request.QueryString["Role"].ToString() :
"0");
instead of
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
You need to check for null if not passed query string.
first thing
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
This statement is outside try so if it crashes on QueryString being null or even if Convert.ToInt32 method throw exception, catch block will not be executed.
You can try this code
int number;
bool result = Int32.TryParse(Request.QueryString["Role"], out number);
if (result)
{
// your implemntation
}
else
{
// your implemntation
}
You can even use Convert.ToString(Request.QueryString["Role"]) if still u are getting this error.
The code is trying to access a member of a reference type variable that is set to null.
Please make source Request.QueryString["Role"] is not null.
You should Never catch NullReferenceException.
However, the problem seems to be in very first line: (the only line outside try block)
int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
either Request is null OR QueryString["Role"] is returning null.
Share the stack trace for more clear answer.
So I took over this project and one page is throwing a lot of errors. I would need to refactor the whole thing but as always time is an issue.
In one case the code check's whether a datareader has any rows and if not go to an error page. However as the code is now the datareader can be null (didn't successfully connect to db) and in those cases I can't use
if (!dr.HasRows)
//
becasuse it obviously gives me 'nullreferenceexception was unhandled by code'. I tried with !dr.Read but same thing.
A part of the code is something like
SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
}
catch
{
//show an error message
}
// and then:
if (!dr.HasRows)
{
}
Any suggestions?
Thanks in advance.
What about:
if (dr == null || !dr.HasRows) {
// Do something
}
One possibility is:
SqlDataReader dr = null;
try
{
//connect to db etc
dr = DbHelper.GetReader("sp_GetCustomer", param);
if (!dr.HasRows)
{
}
}
catch
{
//show an error message
}
Hai,
In my code while executing a function i got regularly the exception error as "Object reference not set to an instance of an object"
The function exceuting is as follows
private void PageHeaderSetting(Graphics g)
{
try
{
DataTable dtPageHeader=new DataTable() ;
dtPageHeader = ds.Tables["Page Header"];
if (dtPageHeader.Rows.Count != 0)
{
foreach (DataRow dr in dtPageHeader.Rows)
{
if (dr.ItemArray[0].ToString() != "")
PageHeaderText = dr.ItemArray[0].ToString();
else
PageHeaderText = "";
if (dr.ItemArray[1].ToString() != "")
PageHeaderFont = (Font)dr.ItemArray[1];
else
PageHeaderFont = new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point);
if (dr.ItemArray[2].ToString() != "")
PageHeaderFormat = AlignmentSetting(dr.ItemArray[2].ToString());
else
PageHeaderFormat = AlignmentSetting(Convert.ToString(Alignment.Left));
if (dr.ItemArray[3].ToString() != "")
PageHeaderColor = (System.Drawing.Color)dr.ItemArray[3];
else
PageHeaderColor = Color.Black;
PageFooterText = Word_Wrap(PageHeaderText, PageHeaderFont, g, 0);
PageHeader(g);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can i solve this.Can anybody help me?
From the second line i got the exception error
means after declaring the datatable and putting the ds.Tables in it from there erroe occurs
This exception means you're trying to call a method on a null object. The exception should have given you a stack trace with the line number it was thrown at; this'll help you pin it down a bit. You could also try debugging it in visual studio and see where the exception is thrown & see what is null.
Instead of using ToString() to check if you have a value in the ItemArray you should check the actual value. Check for ItemArray[0] == null and ItemArray[0] == DBNull.Value.
Edit:
From your comment it seems that there may not be any data table named "Page Header" in your data set.
Try to add a null check to your DataTable object after the line dtPageHeader = ds.Tables["Page Header"];
Something like this:
if (dtPageHeader == null)
{
// There is no table named Page Header
}
Look at the line number in the exception.
Your code has numerous chained calls, which is a common source of this exception. If either of these chained properties returns null, the "next" call in the chain will fail with a NullReferenceException.
One of this could be true:
ds is null
A Value on a columun in dtPageHeader is null