简体   繁体   中英

ExecuteReader- An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

I am getting the above mentioned error everytime I try to run this particular web page. I am adding some code and an image of the database structure (given as a link). In the additional information line of the error, it says there has been attempt to read data when the data table is empty. When I go back to check the table data, there is data present. Please help!

SqlConnection con = new SqlConnection(@"ConnectionString");
protected void Page_Load(object sender, EventArgs e)
{
    string checkdu = "select Top 1 Hour, Minute, Hour1, Minute1 from Clockin";
    SqlCommand cmddu = new SqlCommand(checkdu, con);
    con.Open();
    SqlDataReader dru = cmddu.ExecuteReader();
    int td1 = (Convert.ToInt16(dru["Hour"]) * 60) + (Convert.ToInt16(dru["Minute"]));      //error shown here[enter image description here][1]
    int td2 = (Convert.ToInt16(dru["Hour1"]) * 60) + (Convert.ToInt16(dru["Minute1"]));

You have to use SqlDataReader.Read to advance the reader to the next(first) record:

using(var dru = cmddu.ExecuteReader())
{
    if(dru.Read())
    {
        int td1 = (Convert.ToInt16(dru["Hour"]) * 60) + (Convert.ToInt16(dru["Minute"]));      //error shown here[enter image description here][1]
        int td2 = (Convert.ToInt16(dru["Hour1"]) * 60) + (Convert.ToInt16(dru["Minute1"]));
    }
}

Remarks :

The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.

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