SqlDataReader - how to discover that column is empty - c#

I try to read the result of the query and discover if some of the columns is empty
This is a way I started:
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
rdr["ColumnName"]; // how do I know if it has a value or empty
}
I thought to do :
dr[4].ToString() == String.Empty
It makes a needed work, but I don`t like this (it is a hack rather than solution)
can you advise me how do I do it correctly and elegantly?

Empty does not exists for int values and what is correct when working with databases is use Null which is the only true "Empty".
SqlDataReader rdr = cmd.ExecuteReader();
int colIndex = read.GetOrdinal("MyColumnName");
while (rdr.Read())
{
// [true | false] your validation goes here!;
if (rdr.IsDBNull(colIndex)){
//value is null
}
}
Please note that if you want use 0, "" or 1/1/1900 as empty values those will require a custom treatment.

This is how I do it
string UserInitialssql = rdr.IsDBNull(2) ? String.Empty : rdr.GetString(2);
If it is Int
Int32? i = rdr.IsDBNull(2) ? (Int32?)null : rdr2.GetInt32(2);

Another possibility is to use nullable types. e.g.:
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int? someNumber = rdr["ColumnName"] as int?;
if (someNumber == null)
// was NULL in database
else
// use someNumber.Value to get int
}

Related

Reader.Read() didn't read any row even though it has 1 row [duplicate]

private void button1_Click(object sender, EventArgs e)
{
string name;
name = textBox5.Text;
SqlConnection con10 = new SqlConnection("con strn");
SqlCommand cmd10 = new SqlCommand("select * from sumant where username=#name");
cmd10.Parameters.AddWithValue("#name",name);
cmd10.Connection = con10;
cmd10.Connection.Open();//line 7
SqlDataReader dr = cmd10.ExecuteReader();
}
if ( textBox2.Text == dr[2].ToString())
{
//do something;
}
When I debug until line 7, it is OK, but after that dr throws an exception:
Invalid attempt to read when no data is present.
I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.
Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
You have to call DataReader.Read() to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for single/first record here
}
DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.
I just had this error, I was calling dr.NextResult() instead of dr.Read().
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
I used the code below and it worked for me.
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue

How to get the value of sql (sum) query in textbox? [duplicate]

private void button1_Click(object sender, EventArgs e)
{
string name;
name = textBox5.Text;
SqlConnection con10 = new SqlConnection("con strn");
SqlCommand cmd10 = new SqlCommand("select * from sumant where username=#name");
cmd10.Parameters.AddWithValue("#name",name);
cmd10.Connection = con10;
cmd10.Connection.Open();//line 7
SqlDataReader dr = cmd10.ExecuteReader();
}
if ( textBox2.Text == dr[2].ToString())
{
//do something;
}
When I debug until line 7, it is OK, but after that dr throws an exception:
Invalid attempt to read when no data is present.
I don't understand why I'm getting that exception, since I do have data in the table with username=sumant.
Please tell me whether the 'if' statement is correct or not. And how do I fix the error?
You have to call DataReader.Read() to fetch the result:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read())
{
// read data for single/first record here
}
DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:
while (dr.Read())
{
// read data for each record here
}
You have to call dr.Read() before attempting to read any data. That method will return false if there is nothing to read.
I just had this error, I was calling dr.NextResult() instead of dr.Read().
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
I used the code below and it worked for me.
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue

How to make Sqlcommand accept null values

I'm trying to get data in a gridview from a database to show up in text boxes upon clicking and it works fine for the rows with no null data, although since my int columns have some null values my GetInt32 methods keep returning "Data is Null. This method or property cannot be called on Null values."
Is there a simple way to fix or work around this? Do I replace GetInt32 with another method? I'd like for the data that is null to show up blank/empty in the text boxes if possible. Here's my code if you have any suggestions, thanks.
public ArrayList GetAllPersonnel(int WorkerID) {
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
String query = "Select * FROM Personnel WHERE WorkerID = " + WorkerID;
using (var command = new SqlCommand(query, connection)) {
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read()) {
String firstname = reader.GetString(1);
String lastname = reader.GetString(2);
String occupation = reader.GetString(3);
String deployment = reader.GetString(4);
int disasterid = reader.GetInt32(5);
String location = reader.GetString(6);
int deployedhours = reader.GetInt32(7);
int resthours = reader.GetInt32(8);
list.Add(firstname);
list.Add(lastname);
list.Add(occupation);
list.Add(deployment);
list.Add(disasterid);
list.Add(location);
list.Add(deployedhours);
list.Add(resthours);
}
connection.Close();
reader.Close();
return list;
}
}
}
You should use IsDBNull method of the SqlDataReader
int resthours = (!reader.IsDBNull(8) ? reader.GetInt32(8) : 0);
or, more directly
list.Add((!reader.IsDBNull(8) ? reader.GetInt32(8).ToString(): string.Empty));
Said that, I have noticed that you use a string concatenation to build the sql command text to retrieve records. Please do not do that. It is very dangerous and could lead to Sql Injection
String query = "Select * FROM Personnel WHERE WorkerID = #wkID";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#wkID", WorkerID);
var reader = command.ExecuteReader();
....
OK, so you're effectively saying that everything you display should be a string type, which is fine, I'm just making that point because you stated you want even integers to show up as an empty string. So how about this code?
String firstname = reader.GetString(1);
String lastname = reader.GetString(2);
String occupation = reader.GetString(3);
String deployment = reader.GetString(4);
String disasterid = reader.IsDBNull(5) ? string.Empty : reader.GetString(5);
String location = reader.GetString(6);
String deployedhours = reader.IsDBNull(7) ? string.Empty : reader.GetString(7);
String resthours = reader.IsDBNull(8) ? string.Empty : reader.GetString(8);
list.Add(firstname);
list.Add(lastname);
list.Add(occupation);
list.Add(deployment);
list.Add(disasterid);
list.Add(location);
list.Add(deployedhours);
list.Add(resthours);
Now, the reason I stated that you want to leverage everything as a string is because the default value for a int is 0 and that wouldn't meet the empty text box requirement.
You have at least two ways to sort this out
Modify your sql to select either zero or whatever you think suitable in the place of null value. This will ensure that you always have an integer value in the integer column. It can be done in the following manner
select ISNULL ( ColumnName , 0 ) as ColumnName from xxx
Always fetch object from the reader and check if it is null or not. If it is null then replace it with suitable value.

Check if a datareader has rows or not in Asp.net

My code:
string sqlQuery1 = "select * from employees where depid=6";
SqlDataReader Dr1 = dbconn.RunQueryReturnDataReader(sqlQuery1);
if(Dr1.read()) { //or if (Dr1["empname"] != DBNull.Value)
while (Dr1.Read())
{
Label1.Text = Dr1["empname"].ToString();
Label2.Text = Dr1["empdes"].ToString();
...
}
Dr1.Close();
}
else {
Label1.text = "defaultValue";
Label2.text = "defaultValue";
...
}
I just want to check SqlDataReader has no records to display. If no records ,the labels should showdefault values preassigned by me or If has record display datareader value on label. (Assume either SqlDataReader has 1 recode or has norecord only)
How can I check first datareader hasRow or not?
I have tried two ways as above code.
if(Dr1.read()) - this way working fine. But after execute If statement ,it has no value to display on labels , since read() will increase the pointer. As a result label1 ,Label2.. Nothing display.
if (Dr1["empname"] != DBNull.Value)
This way generate an exception when Sqldatareader has norows.
error: System.InvalidOperationException: Invalid attempt to read when no data is present
Please help me. tx
try...
if(Dr1.HasRows)
{
//....
}
if (Dr1 == null || !Dr1.HasRows) {
// Do something
}

sqldatareader error

I want to check if the sqldatareader is null or not. So tried the following code:
if (x[k]!= DBNull.Value)
{
box.Text = Convert.ToString(x[k++]);
if ((box.Text) != "")
current[j - 1] = Convert.ToDouble(box.Text);
else current[j - 1] = 0;
box.Enabled = false;
}
However while trying to check the value within the datareader, it throws an error,"invalid attempt to read data when no data is present". How else should i check to see if data is there or not.!! please help. here x is an sqldatareader
SqlDataReader x = cmd.ExecuteReader();
and cmd is a select commnand..
You can use SqlDataReader.HasRows - it is true if at least one row of data is present, alternatively you can read through all results using SqlDataReader.Read();
So for your example:
while(x.Read())
{
//read stuff
}
You can do a null check and Has Row before accessing the DataRows.
like this
if(null != x && x.HasRows)
{
//Your code
}

Categories