简体   繁体   中英

mysql select query skipping first row values

There is only a drop down list with student ID and a grid view with students' images in my web page. If I select a student Grid View has to show all the images of the selected student. Problem is when I select a student my grid view is skipping first two values. I mean if there are 6 images grid view shows only 4 images. Here is my code:

private void BindGrid()
{
    MySqlConnection con = new MySqlConnection(constr);
    MySqlCommand cmd = new MySqlCommand("SELECT * FROM images where Image_ID in (" + String.Join(",", getImage_ID()) + ")", con);
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    gvImages.DataSource = dt;
    gvImages.DataBind();
}
private List<int> getImage_ID()
{
    List<int> i = new List<int>();
    MySqlConnection con = new MySqlConnection(constr);
    con.Open();
    string query = "Select Come_Image_ID1, Leave_Image_ID from register where Students_ID='" + getStudents_ID() + "' AND Come_Image_ID IS NOT NULL AND Leave_Image_ID IS NOT NULL"; 
    MySqlCommand cmd = new MySqlCommand(query);
    cmd.Connection = con;
    MySqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        foreach (DbDataRecord s in reader)
        {
            i.Add(s.GetInt32(0));
            i.Add(s.GetInt32(1));
        }
    }
    reader.Close();
    return i;
}

What is the best coding practice for this issue?

You are mixing ways to read data. Either you a while loop:

while (reader.Read())
{
    i.Add(reader.GetInt32(0));
    i.Add(reader.GetInt32(1));
}

Or a foreach loop:

foreach (DbDataRecord s in reader)
{
    i.Add(s.GetInt32(0));
    i.Add(s.GetInt32(1));
}

But not both. Both the while and the foreach consume records from the cursor, and when you mix them like this you skip the records the while loop consumes.

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