Reputation: 1157
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.
Upvotes: 6
Views: 7740
Reputation: 337
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();
Upvotes: 0
Reputation: 184
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);
}
}
...
Upvotes: 5
Reputation: 887195
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
.
Upvotes: 8