Search code examples
c#sql-server-ce

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;
    }

Solution

  • 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();