how to check if a datareader is null or empty - c#

I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time empty or null.
I am trying to write code that checks if this field isnull. The logic behind this is:
If the field "Additional" contains text then display the info otherwise hide the field.
I have tried:
if (myReader["Additional"] != null)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
The above code gives me this error:
Exception Details: System.IndexOutOfRangeException: Additional
Any help would be greatly appreciated...
See Also:
Check for column name in a SqlDataReader object

if (myReader["Additional"] != DBNull.Value)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}

if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}

I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:
public static class DataReaderExtensions
{
public static bool IsDBNull( this IDataReader dataReader, string columnName )
{
return dataReader[columnName] == DBNull.Value;
}
}
Kevin

This is the correct and tested solution
if (myReader.Read())
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null";
}

I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }

First of all, you probably want to check for a DBNull not a regular Null.
Or you could look at the IsDBNull method

In addition to the suggestions given, you can do this directly from your query like this -
SELECT ISNULL([Additional], -1) AS [Additional]
This way you can write the condition to check whether the field value is < 0 or >= 0.

#Joe Philllips
SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?

Try this simpler equivalent syntax:
ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";

I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:
DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");
using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

Best thing to get this done in query. However, if query bond to other functions than checking DBNull.Value in while loop would address the issue.
if (reader.HasRows)
{
while (reader.Read())
{
(reader["Additional"] != DBNull.Value) ? "contains data" : "is null";
}
}

AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.
I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"

Related

How to check a field empty or not in MySQL / C#

I have a table for stock transfer and there is a integer field called trnsno. I need to get the max value of that. If it is empty, the trnsno is 1.
sql = "SELECT MAX(`trnsno`) FROM stktransfer";
//...
//...
if (config.dt.Rows.Count > 0)
{
if (string.IsNullOrEmpty(Convert.ToString(config.dt.Rows[0].Field<int>(0))))
{
strTrnsNo = "1";
}
else
{
strTrnsNo = (Convert.ToInt32(config.dt.Rows[0].Field<int>(0)) + 1).ToString();
}
}
It says " Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type."
I am new to C# and please help me on this.
You can do the check in c# by comparing to DbNull.Value:
object objTrnsNo = config.dt.Rows[0][0];
strTrnsNo = DbNull.Value.Equals(objTrnsNo) ? "1" : objTrnsNo.ToString();
You can use IFNULL to check for NULL and this example would return -1 instead
SELECT IFNULL(MAX(`trnsno`),-1) FROM stktransfer

Override ToString of a Null Object? C# asp.net

I have a List<> of say People, and people have an instance of a Thought object, I display People in a gridview, there is one column for each variable of the People Class and one for Thoughts, which displays the Thought's class Tostring Override, when I delete a thought, if it was used by any given "People" It would set that People's thought to "null" but when I try to retrieve that "null" from the db (ADO.NET) I get an error (which I think doesn't matter atm), how can I display a "NULL" on the gridview of People in which thoughts have been deleted?
EDIT:
Here is the method I use to save the DATASET:
public List<People> PeopleList()
{
ControllerClass cont = new ControllerClass();
List<People> list = new List<People>();
string strSQL = "SELECT * FROM People";
DataSet data = Select(strSQL);
if (data.Tables[0].Rows.Count > 0)
{
foreach (DataRow Row in data.Tables[0].Rows)
{
People p = new People();
p.IdPeople= Convert.ToInt32(Row.ItemArray[0].ToString());
p.NamePeople= Row.ItemArray[1].ToString();
p.ThoughtPeople= cont.SearchThought(Convert.ToInt32(Row.ItemArray[3].ToString()));
list.Add(p);
}
}
return list;
}
I use a method to search for thoughts because I save the thought's ID as a foreign key
Handle it like
p.NamePeople= Row.ItemArray[1] == DBNull.Value ? "NULL" : Row.ItemArray[1].ToString():

Generated FindBy() always returns null

I have a dataset (myds) that contains table (assests).
When I try to find a row in (assest) by using the auto-generated FindBy() it always returns null.
MyDS.AssestsRow asRow = this.myds.Assests.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
I'm 100% sure that I have row in the table that matches my query but this FindBy() always returns null!
Any ideas?
Here we go,
Although I couldn't figure it out yet but I found that after declaring Assets datatable and using AssetsTableAdapter to get data into it, only then, I was able to retrieve the row I wanted.
So instead of doing this:
MyDS.AssestsRow asRow = this.myds.Assests.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
I did that:
MyDS.AssestsDataTable assetsDataTable = this.assestsTableAdapter.GetData();
MyDS.AssestsRow asRow = assetsDataTable.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
Anyone could tell me WHY?

I can't seem to check a value in a particular column of a datatable. Why?

I have a datatable with data in it (customer addresses). In some instances, column ADDR3 doesn't have a value and column ADDR2 does. I'm attempting to check the value of ADDR3 and if it doesn't contain a value I want to copy the value in ADDR2 to ADDR3 and then blank out ADDR2. I was trying to use the below code, but it isn't working. I placed a breakpoint after my 'if' statement, but the program never breaks. But, I know for a fact that a lot of the rows have null ADDR3 fields. Can anyone tell me what I'm doing wrong?
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
object value = row["ADDR3"];
if (value == DBNull.Value)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}
It's likely that your row["ADDR3"] value is NEVER equal to DbNull.Value. This is often the case with data tables that were transferred over a web service, for example (there will be empty strings instead of nulls due to the XML transformations).
Put a break point BEFORE your if and find exactly what the value is. You might try checking for row["ADDR3"] == null or string.IsNullOrWhiteSpace(row["ADDR3"].ToString())
Have you tried comparing the value to null (rather than DBNull.Value)? I believe DBNull.Value is exclusive for certain database objects and does not appear once read into a dataset/datatable.
Try this:
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
if (
row.IsNull("ADDR3") // True if the value is null
||
String.IsNullOrWhitespace(row["ADDR3"]) // True if the value is "", " ", etc.
)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}

Data Reader Returning null although it says it has an item there

hello I am using a reader to get a XML from a stored procedure.. now the stored procedure returns null if it does not find anything .. in the case I am testing.. it should not return anything but my code is failing.. it says there is a row.. but then when it gets to the reader.GetString(0); it says Data is Null. This method or property cannot be called on Null values.
How can I check for null int hat line XML = XML + reader.GetString(0);? it is passing the while(reader.Read() && reader.HasRows) check.. when I debug it says there is an item but then when it gets to the line mentioned above it throws the Data is null error. How can I fix this?
Here is my code
SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
string XML = "";
while (reader.Read() && reader.HasRows)
{
XML = XML + reader.GetString(0);
}
XML = "<ProductList>" + XML + "</ProductList>";
reader.Close();
myConnection.Close();
return XML;
Use IsDBNull first:
if (!reader.IsDBNull(0))
{
XML = XML + reader.GetString(0);
}
You can use IsDBNull method to check for null:
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
XML = XML + reader.GetString(0)
}
}
UPDATE Removed the reader.HasRows call as it's redundant (as pointed out by someone else).
If I remember correct, the while (reader.Read() will make it go through the loop once even if there isn't data. Could be mistaken on that though. Couple things you can try are changing it to have a nested if like
while(reader.read())
{
if(reader.HasRows)
{
XML = XML + reader.GetString(0);
}
}
I would change the GetString(0) to GetValue(0).ToString(); May not make a difference but GetString and GetValue behave differently when nulls are involved.

Categories