Leo Storm
Leo Storm

Reputation: 37

DataReader error - "no data exist for the row/column" - when data exists?

I need some help in understanding my error. I want to read data from table, however I get error such as "no data exist for the row/column". I dont understand it, since I actually have rows and columns in there. WinForms. Thanks!

    //this is how i insert data into table, works fine 
    public void b1_Click(object sender, EventArgs e)
    {
        SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn);
        command.Parameters.AddWithValue("@Name", l1.Text);
        command.ExecuteNonQuery();
    }

    //this is how i try to read data from the same table
    public void b2_Click(object sender, EventArgs e)
    { 
       SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:test.sdf");
       conn.Open();
       SqlCeCommand command = new SqlCeCommand("SELECT * FROM  tbl1", conn);
       SqlCeDataReader reader = command.ExecuteReader();

       //error here
       string Name = reader.GetString(0);
       label.Text = Name;
    }

Upvotes: 1

Views: 6682

Answers (2)

RichardTheKiwi
RichardTheKiwi

Reputation: 107686

In this sequence

    SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name, LastName) VALUES (@Name, @LastName)", conn);
    command.Parameters.AddWithValue("@Name", l1.Text);
    command.ExecuteNonQuery();

You're not setting the 2nd parameter @LastName so it should have failed. If you didn't previously have records in the table, you would have nothing to select from.

That, and the fact that you are not calling reader.Read()

Upvotes: 1

Erre Efe
Erre Efe

Reputation: 15557

Problem is with your results' loading.

SqlCeDataReader reader = command.ExecuteReader();

while (reader.Read())
{
   string Name = reader.GetString(0);
}

So you use the Read method to iterate through the results. Or, if you just have one result then you can also use the ExecuteScalar

string Name = reader.ExecuteScalar().ToString();

Upvotes: 1

Related Questions