user1955449
user1955449

Reputation:

Invalid attempt to call Read when reader is closed

I am having a problem with the sql datareader. Whenever I try to read data it gives me an error saying invalid attemp to call Read when the reader is closed. Please help me figure out the problem

private void button1_Click(object sender, EventArgs e)
    {
        string name = this.textBox1.Text;
        string connstring = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Gardezi\Documents\Visual Studio 2012\Projects\homeWork2\homeWork2\Database1.mdf;Integrated Security=True";
        SqlConnection con = new SqlConnection(connstring);
        string query = "Select * from diaryDB";
        SqlCommand com = new SqlCommand(query, con);
        SqlParameter p = new SqlParameter("name", name);
        con.Open();
        SqlDataReader d =  com.ExecuteReader();
        con.Close();
        deleteResult r = new deleteResult(d);
        r.Show();
    }

this is the constructor of deleteResult

public deleteResult(SqlDataReader d)
    {

        InitializeComponent();
        while (d.Read())
        {
            this.comboBox1.Items.Add((d["Title"] +"-" +d["Description"]).ToString());
        }
    }

Upvotes: 0

Views: 545

Answers (2)

Steve
Steve

Reputation: 216363

Please try to use the using statement that correctly enclose the connection, the command and the reader in appropriate blocks.

private void button1_Click(object sender, EventArgs e)
{
    string name = this.textBox1.Text;
    string connstring = @"....";
    string query = "Select * from diaryDB";
    using(SqlConnection con = new SqlConnection(connstring))
    using(SqlCommand com = new SqlCommand(query, con))
    {
        SqlParameter p = new SqlParameter("name", name);
        con.Open();
        using(SqlDataReader d =  com.ExecuteReader())
        {
           deleteResult r = new deleteResult(d);
           r.Show();
        }
    }
 }  

In this way the connection is kept open while you read from the reader. This is essential to avoid the error.

The more important point is that you don't have to worry to close and dispose the connection when it is no more needed. The exit from the using block close and dispose the connection, the command and the reader ALSO in case of exceptions.

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

You can't read after closing the connection. Just change this part of your code:

FROM

(...)
con.Close();
deleteResult r = new deleteResult(d);
(...)

TO

(...)
deleteResult r = new deleteResult(d);
con.Close();
(...)

Upvotes: 1

Related Questions