MinhNguyen
MinhNguyen

Reputation: 856

Error of displaying data from database

I want to display data in database to textbox of my WPF app. With this code below, it worked fine.

private void Button_Click(object sender, RoutedEventArgs e)
    {
        sqlCon = new SqlConnection(conStr);
        string sqlCmd = "select * from RTF ";
        sqlCon.Open();
        SqlCommand sc = new SqlCommand(sqlCmd, sqlCon);
        SqlDataReader rdr = sc.ExecuteReader();
        //sc.Dispose();

        while (rdr.Read())
        {
            string filename = rdr.GetString(1);
            rtb.Text = filename ;
        }

        rdr.Close();
        sqlCon.Close();
   }

But if I took of While(rdr.Read()) like below, I would get an exception

An unhandled exception off type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: Invalid attempt to read when no data is present.

Can someone explain why this error happens? I thought it just be enough to retrieve a string from database by specifying:

string filename = rdr.GetString(1) 

so no need to do a loop but apparently its not the case here. Any ideas?

private void Button_Click(object sender, RoutedEventArgs e)
{
            sqlCon = new SqlConnection(conStr);
            string sqlCmd = "select * from RTF ";
            sqlCon.Open();
            SqlCommand sc = new SqlCommand(sqlCmd, sqlCon);
            SqlDataReader rdr = sc.ExecuteReader();
            //sc.Dispose();

                string filename = rdr.GetString(1);
                rtb.Text = filename ;

            rdr.Close();
            sqlCon.Close();
}

Upvotes: 0

Views: 34

Answers (1)

Grant Winney
Grant Winney

Reputation: 66479

From the documentation on MSDN:

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

So you have to perform a read at least once before trying to get a value.

You don't necessarily need a loop for that:

rdr.Read();
rtb.Text = rdr.GetString(1);

Although if all you need is one column from one row, you may want to read up on ExecuteScalar.

Upvotes: 1

Related Questions