Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello

I need to retrieve information from database
what the code I should use

C#
string ip;
                        ip = GetIP();
                        SqlCommand command = new SqlCommand("SELECT DeviceName FROM ConnectedDevice  WHERE IP= @IP AND IDName=@IDName  ", connection);
                        command.Parameters.Add(new SqlParameter("@IP", ip));
                        command.Parameters.Add(new SqlParameter("@IDName", name));
                        command.ExecuteNonQuery();

                        SqlDataReader reader1 = command.ExecuteReader();
                         if (reader1.HasRows)
                            {

                                device = reader1.GetValue(0).ToString();
                                
                              
                            }


the code
C#
device = reader1.GetValue(0).ToString();


do not retrieve any thing and give an error
what the code should I replace it with ??

thanks :)
Posted

Take a look here: SqlDataReader Class[^] - on the bottom of page you'll find a solution: how to read data from datareader?
 
Share this answer
 
v2
Comments
maxpower12345 24-May-12 5:14am    
thanks

but still give an error :(

"invalid attempt to read when no data is present "

while the is data in database
maxpower12345 24-May-12 5:20am    
thanks its work :)
Sandeep Mewara 24-May-12 5:37am    
Good answer. 5!
Maciej Los 24-May-12 5:53am    
Thank you, Sandeep ;)
To start for a select statement, replace
C#
command.ExecuteNonQuery();

with
C#
SqlDataAdapter sqlDa = new SqlDataAdapter(command);
DataSet ds= new DataSet();
sqlDa.Fill(ds);
 
Share this answer
 
Instate of this
C#
if (reader1.HasRows)
{
       device = reader1.GetValue(0).ToString();
}

Write this
C#
if (reader1.HasRows)
{
   if(reader1.Read())
   {
       device = reader1.GetValue(0).ToString();
   }
}

and you can remove this line(delete this line)
C#
command.ExecuteNonQuery();
 
Share this answer
 
v2
You can use like this also

C#
 if (reader1.HasRows)
{
 while(reader1.Read())
  {
     device = reader1["your column name"].ToString();
  }
}
 
Share this answer
 

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