Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SqlDataReader No data exists for the row/column

I've been away from programming for a while but recently I've got a need for it.

I have a problem with SQL DataReader using Sql Server Compact Edition 4.0 (VS2012 Built-in).

string connstring = "Data Source=C:\\..(Path Here)..\\VacationsDB.sdf";
SqlCeConnection conn = new SqlCeConnection(connstring);
string strSQL = "SELECT * FROM Vacation WHERE VacationNo = @val";

using (SqlCeCommand cmd = new SqlCeCommand(strSQL, conn))
{
    //read search value from from text field
    cmd.Parameters.AddWithValue("@val", vacationno_txt.Text);
    conn.Open();

    SqlCeDataReader reader = cmd.ExecuteReader();
    fname_txt.Text = reader.GetString(0);
    mname_txt.Text = reader.GetString(1);
    /*
     * .. snip
     */
    vacationno_txt.Text = reader.GetString(11);
    conn.Close();
}

I keep getting the error: "InvalidOperationException was Unhandled. No data exists for the row/column." And the error points at fname_txt.Text = reader.GetString(0);

But there is actually data there because the "Submit" button with all it's code is working and I've checked it in the database table itself.

Any tips? Thank you.

like image 559
Yousef Imran Avatar asked Aug 09 '13 21:08

Yousef Imran


1 Answers

DataReaders start out before the first row.

To read from the first row, call Read() once.
If there is no first row, Read() will return false.

like image 164
SLaks Avatar answered Sep 28 '22 09:09

SLaks