Click here to Skip to main content
15,891,936 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Please someone tell that how to read value from database from datareader in asp.net c#. I have done my code but it throwing an error that dr is variable but is used like a method.
This is my code :

C#
cmd = new SqlCommand("select * from Images where id=" + DropDownList1 .SelectedValue + "",con);
            cmd.ExecuteReader();

            while(dr.Read ())
            {
                TextBox1.Text = dr(1);
            }



Please some one tell the solution

Thanks.
Posted
Updated 21-Apr-11 1:34am
v2

Initialize dr like this :

SqlDataReader dr = cmd.ExecuteReader;

SQL
cmd = new SqlCommand("select * from Images where id=" + DropDownList1 .SelectedValue + "",con);
           SqlDataReader dr =  cmd.ExecuteReader();
            while(dr.Read ())
            {
                TextBox1.Text = dr[1].ToString();
            }
 
Share this answer
 
v3
Comments
Toniyo Jackson 21-Apr-11 7:40am    
Correct. My 5
Tarun.K.S 21-Apr-11 7:53am    
Thanks buddy.
Member 10037441 8-May-13 11:15am    
The solution was excellent! It helped me populate a listbox with the results of a query.
Change
TextBox1.Text = dr(1);
To
TextBox1.Text = dr[1];


In addition, try using the field name instead of a number, particularly if you are going to return all fields via the "*" specifier - you don't say what order to return the fields in, so you don't know if column 1 exists, or what it contains...
 
Share this answer
 
Comments
Toniyo Jackson 21-Apr-11 7:40am    
Correct. My 5
Check this links. These will help you.

http://msdn.microsoft.com/en-us/library/haa3afyz%28v=VS.80%29.aspx[^]

http://blog.mdsohelrana.com/2008/07/02/how-to-use-datareader-in-cnet/[^]

I think you should use like this.
TextBox1.Text = dr[1];
 
Share this answer
 
v3
Comments
Tarun.K.S 21-Apr-11 7:56am    
Updated the first link to include the C# version. 5+
Toniyo Jackson 21-Apr-11 7:58am    
Thanks Tarun
try to find out in the following way


int Id = int.parse(DropDownList1 .SelectedValue);

SQL
cmd = new SqlCommand("select * from Images where id= @Id",con);
cmd.parameters.addwithvalue("@Id",Id);




MIDL
while (dr.Read())
            {
                objProduct.ProductImage = dr["Imagename"].ToString();
            }
 
Share this answer
 
Comments
Tarun.K.S 21-Apr-11 7:56am    
How is this going to solve the problem?
Mahendra.p25 21-Apr-11 8:00am    
i just told him the way not exact solution
Tarun.K.S 21-Apr-11 8:09am    
But if you tell him the exact solution first and then the way, it could solve the OP's answer better. OP doesn't know how to use the ExecuteReader command.
Mahendra.p25 21-Apr-11 8:12am    
suggestion accepted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900