Click here to Skip to main content
15,918,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is an error within while loop?

C#
protected void Page_Load(object sender, EventArgs e)
    {
        string path = "Data Source=192.168.1.14;Initial Catalog=nazer;User ID=sa;Password=admin*123";
        SqlConnection con = new SqlConnection(path);
        con.Open();
        string query = "select MAX(id) from tbl_samp1";
        SqlCommand cmd = new SqlCommand(query, con);        
        SqlDataReader dre=cmd.ExecuteReader();
        while (dre.Read())
        {        
           // int values = int.Parse(dre["id"].ToString());  //pls give any alternate code within while loop.Error occured in this line.
        int values = (int)dre["id"];
        TextBox1.Text = values.ToString();            
        }      
        con.Close();        
    }
Posted
Updated 7-Feb-12 18:58pm
v3

Have A Look At This Article

http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.90).aspx[^]

Accept This Answer If It Has Helped You
 
Share this answer
 
Before executing while loop, you should validate whether you have valid records as:
C#
while (dre.Read())
            {


C#
if (dre.HasRows)
       {
           while (dre.Read())
           {


It is good practice to trace the exception using try..catch block
 
Share this answer
 
Comments
Aniket Yadav 8-Feb-12 1:08am    
Exactly... This Is The Better Practice Of Coding

Thanks GanesanSenthilvel
Hi Sir,

Yes, as Sen said you must always validate your dr to check if there is a rows or nothing.

And you can try to convert your dr into toString().

Thank You.
 
Share this answer
 
Comments
murugeshchinnu 8-Feb-12 3:56am    
Thank you.
SqlCommand.ExecuteScalar()
return the data of first row,first column.
C#
string path = "Data Source=192.168.1.14;Initial Catalog=nazer;User ID=sa;Password=admin*123";
SqlConnection con = new SqlConnection(path);
con.Open();
string query = "select MAX(id) from tbl_samp1";
SqlCommand cmd = new SqlCommand(query, con);        
int values = Convert.ToInt32(cmd.ExecuteScalar());
TextBox1.Text = values .ToString();
 
Share this answer
 
Comments
murugeshchinnu 8-Feb-12 3:56am    
Thank you so much
murugeshchinnu 8-Feb-12 4:33am    
your coding very helpful for me thanks

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