Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SqlDataReader problem 1

Status
Not open for further replies.

xanra

IS-IT--Management
Jan 16, 2007
20
US
Hi in my code block if i have only one of the text boxes display data it works fine. It doesnt matter whether it is txtPBatch and txtPDate but not both of them at once. when i set it to display for both of my text boxes i get the following error.

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at Benefits_WhosWhereRetirement.Page_Init(Object sender, EventArgs e) in


below is my code:

Code:
string conString1 = ConfigurationManager.ConnectionStrings["Y5351ConnectionString"].ConnectionString;

        SqlConnection sql = new SqlConnection(conString1);
        string query = "select top 1 batchID as[BatchID],Convert(varchar(10),date,1)as Date from whoswhere";
        SqlCommand cmd = new SqlCommand(query, sql);
        SqlDataReader rdr = null;
        
        

        try
        {
            sql.Open();
            rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            if (rdr.Read())
            {
       

                txtPBatch.Text = (string)rdr["BatchID"];
            txtPDate.Text =  (string)rdr["Date"];

            }


        }
        catch (Exception ex)
        {
            txtPBatch.Text = ex.ToString();
        }

        finally
        {
            
            if (rdr != null)
                rdr.Close();

         
            if (sql.State == ConnectionState.Open)
                sql.Close();

        }

Thanks in advance!
-Paul
 
txtPBatch.Text = rdr["BatchID"].ToString();
txtPDate.Text = rdr["Date"].ToString();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
I would change this section

Code:
            if (rdr.Read())
            {
       

                txtPBatch.Text = (string)rdr["BatchID"];
            txtPDate.Text =  (string)rdr["Date"];

            }


Code:
            while(rdr.Read())
            {
       
            
               //  check for the column here.  if it exists, set the text box text equal to it's value.
            }
 
Thank you very much! I originally had a while but i came across a solution on msdn that recommended an IF block... i changed it back to while and its working.

Thank you both of you!! Really appreciate it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top