Question

The data reader named eventreader can be empty and i'm trying to work out an appropriate statement to detect if the datareader contains rows and if the require record exists.

oledbexecute("SELECT [Unit No] FROM UnitOpenAtEvent WHERE [Event ID]='" + strDate + "'");
            eventReader = dbcommand.ExecuteReader();
            for (int i = 0; i < checkboxEvent.Items.Count; i++)
            {
                if (checkboxEvent.GetItemCheckState(i) == CheckState.Checked)
                {
                    if (eventReader["Unit No"] != DBNull.Value)
                    {
                        while (eventReader.Read())
                        {
                            if (eventReader["Unit No"].ToString() == checkboxEvent.Items[i].ToString())
                            {
                                oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
                                intReader = dbcommand.ExecuteNonQuery();
                            }
                        }
                    }
                    else
                    {
                        oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
                        intReader = dbcommand.ExecuteNonQuery();
                    }
                }
                else if (checkboxEvent.GetItemCheckState(i) == CheckState.Unchecked)
                {

                   // this is effectively a copy of above
                 }
            }
Was it helpful?

Solution

You can check if the DataReader has any rows using e.g.

if (eventReader.HasRows)

Update: Following from comment below re: IDataReader...

You could do something like this (shortened to include the most relevant bits for conciseness)

eventReader = dbcommand.ExecuteReader();
bool hasRow = eventReader.Read();
if (hasRow)
{
    for (int i = 0; i < checkboxEvent.Items.Count; i++)
    {
        ...
            ...
            while (hasRow)
            {
                // Code in here to deal with each row
                hasRow = eventReader.Read();
            }
    }
}

OTHER TIPS

You may be misunderstanding how IDataReader.Read() works.

From that help page:

Return Value
Type: System.Boolean
true if there are more rows; otherwise, false.

and

The default position of the IDataReader is prior to the first record. Therefore you must call Read to begin accessing any data.

So when you first get a datareader it won't be pointing to any data. If you call .Read() it will return true if there is a row to move to and move to it and if there are no rows it will return false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top