Skip to content Skip to sidebar Skip to footer

Datareader Skips First Result

I have a fairly complex SQL query that pulls different types of products from a database based on a customer ID. It pulls three different types of products, identified by their uni

Solution 1:

update

Turned out the problem was a extra dr.Read() call before the loop. See comments.

update

Looking at the code, it seems the databind is in the wrong place -- maybe something like this? Also, I changed it to show the null items... maybe this will expose a logic problem.

while (dr.Read())
{
    try
    {
      string itemValue = dr["fldMachine_ID"].ToString();
      string flatName =  dr["fldMachineName"].ToString();
      if (string.IsNullOrEmpty(flatName)) flatName = "!NULL!";
      if (string.IsNullOrEmpty(itemValue)) itemValue = "!NULL!";
      items.Add(flatName, itemValue);

      string rotaryName = dr["fldRotaryPressName"].ToString();
      if (string.IsNullOrEmpty(rotaryName)) rotaryName= "!NULL!";
      items.Add(rotaryName, itemValue);
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.ToString());
    }

}
// Bind list to ddl.
machines.DataSource = items;
machines.DataValueField = "Value";
machines.DataTextField = "Key";
machines.DataBind();

machines.Enabled = true;

old

Could it be something silly like customers.SelectedValue.ToString().Trim()?

You can run the profiler and see EXACTLY the SQL that the server is executing... then run that in SSMS to see if you still get different results.

Solution 2:

your code sample shows you calling Read on the DataReader twice at the start, that would cause the reader to skip the first row. You should only need the read call in the while loop.

  dr.read();  // unnecessary read call
  while (dr.Read())
  { }

Solution 3:

You are doing the databind inside the read loop. Really you should bind to an enumerable after it has been populated.

Also, look at the command.AddWithValue() method.

Post a Comment for "Datareader Skips First Result"