简体   繁体   中英

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.

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 .

You need to move the reader's (row) position first. And close it when you no longer need it.

...
using(SqlCeDataReader reader = cmd.ExecuteReader())
{
    if (reader.Read())
    {
        fname_txt.Text = reader.GetString(0);
        mname_txt.Text = reader.GetString(1); . . . 
        vacationno_txt.Text = reader.GetString(11);
    }
}
...

Use new datareader if showing 'No Data exist for the Row/Column'

OleDbCommand cmdsearch2 = new OleDbCommand("Select * from tbl_quotation where quotationno = @qno ", con); cmdsearch2.Parameters.AddWithValue("@qno", txt_quotationno.Text); OleDbDataReader drr = cmdsearch2.ExecuteReader();

            if (drr.HasRows)
            {
                while (drr.Read())
                {
                    cmb_customername.Text = drr["customername"].ToString();
                    txt_revno.Text = drr["revno"].ToString();
                    dtp_qdate.Text = drr["qdate"].ToString();
                    txt_paymentterms.Text = drr["paymentterms"].ToString();
                    txt_delivery.Text = drr["delivery"].ToString();
                    txt_freight.Text = drr["freight"].ToString();
                    txt_quotationvalidity.Text = drr["validity"].ToString();


                }
            }
            drr.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM