0

can somebody tell me how does data reader work in following list
and what will the result of............if(dr.Read())..

public List<clsproductprp> RetFind_rec(clsproductprp prp1)
        {
            SqlDataReader dr=null;
            List<clsproductprp> obj = new List<clsproductprp>();
            SqlCommand discmd = new SqlCommand();
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                discmd.CommandText = "spFindFromProduct";
                discmd.CommandType = CommandType.StoredProcedure;
                discmd.Connection = con;
                discmd.Parameters.AddWithValue("@fanProductid", prp1.productidprp);
                dr = discmd.ExecuteReader();

                if(dr.Read())
                {
                    clsproductprp prp = new clsproductprp();
                    prp.productnameprp = dr["Producname"].ToString();
                    prp.Quantityperunitprp = Convert.ToInt32(dr["Quantityperunit"].ToString());
                    prp.unitinStockprp = Convert.ToInt32(dr["unitinstock"].ToString());
                    prp.unitPriceprp = Convert.ToInt32(dr["unitPrice"].ToString());
                    prp.productidprp = Convert.ToInt32(dr["Productid"].ToString());
                    obj.Add(prp);
                }
            }
            catch { }
            finally
            {
                dr.Close();
                discmd.Dispose();
            }
            return obj;
        }

Edited by Ezzaral: Added code tags. Please use them to format any code that you post.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by sebastian3
0

A datareader runs one way, it is fast and very good for printing out info. So with your if(dr.Read()) if the datareader has rows then this code will print out the first row of data to your variables.

btw: It is good pratice to check to see if the reader has rows before you try to read.

0

Actually dr.read() function moves the pointer of the datareader to the next record and also returns true if it exists.Initially, the reader does not point to anything. It is only after you call dr.read() that is points to the first record and then you can read the data. Without calling that it will give error.
In your case if have also checked its return value in the "if" condition.
I guess there is 1 record. for more records, u have to use while(dr.read()).
Hope u get it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.