Sreenath Ganga
Sreenath Ganga

Reputation: 736

Is datatable empty

I had a a function like this

con.Open();
int k = 1;
OleDbCommand cmd1 = new OleDbCommand("select MAX (CUT_ID) from CUTORDER_MASTER ", con);
OleDbDataReader rdr = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
if (dt != null)
{
    if (int.Parse(dt.Rows[0][0].ToString()) != 0)
    {
        k = int.Parse(dt.Rows[0][0].ToString()) + 1;
    }

}

My issue is if there is no value retrieved by query the data table is returning a cell max(cutid) without any value. therefore it skips the null check and if O check and code reaches k = int.Parse(dt.Rows[0][0].ToString()) + 1;
causing Exception incorrect format

Is there any way to solve this issue and check whether the data table is empty

Upvotes: 1

Views: 1181

Answers (5)

Ram Singh
Ram Singh

Reputation: 6918

First of all my question is: why you are using datatable to retrieve single value. If you are not familiar ExecuteScalar Then read about this it will help you in future also. ok now come to the scenario you have used:

There are number of ways to do that:

If you want your result will contain 0 instead of empty value:

1) you can get it from database as below:

select IsNull(MAX(CUT_ID), 0) from CUTORDER_MASTER

2) using code:

if (dt != null)
{
    if (int.Parse(dt.Rows[0][0].ToString()) != null && 
        int.Parse(dt.Rows[0][0].ToString()) != "")
    {
        k = int.Parse(dt.Rows[0][0].ToString()) + 1;
    }
}

3) using code :

if (dt != null)
{
    if(dt.Rows.Count > 0)
    {
        if (int.Parse(dt.Rows[0][0].ToString()) != null && 
            int.Parse(dt.Rows[0][0].ToString()) != "")
        {
            k = int.Parse(dt.Rows[0][0].ToString()) + 1;
        }
    }
}

and many more.

Upvotes: 2

Doan Cuong
Doan Cuong

Reputation: 2614

Try

'select NVL(MAX(CUT_ID), 0) from CUTORDER_MASTER'

This query will return 0 if there's no data in table. I'm not quite good at Oracle but after a quick research, I think this will work

Upvotes: 4

S.M
S.M

Reputation: 776

Instead of ExecuteReader(), use ExecuteScalar() method and store the result in the variable. Then do null check with this variable. You are checking datatable instance.actually you dont need to use datatable in this scenario.

If you want to check with datatable, use datatable.rows.count() method to check how many rows are populated in the datatable.

Upvotes: 3

Damith
Damith

Reputation: 63065

try below

OleDbCommand cmd1 = new OleDbCommand("select MAX (CUT_ID) from CUTORDER_MASTER ", con);
object result = = cmd1.ExecuteScalar();
int k = (result == null || result == DBNull.Value) ? 0: (int)result;

ExecuteScalar returns the first column of the first row in the result set returned by the query

Upvotes: 1

Jimmy
Jimmy

Reputation: 553

select count(*) from CUTORDER_MASTER    

this will also return 0 if no data in table ;)

Upvotes: 1

Related Questions