none
Assign Results of a Query to a Text Box

    General discussion

  • Hi, am trying to teach myself C#.

    I have a form with one label, and one button. I also have a small SQL Server database called Staff, with one table called Users.

    I am trying run a querry that returns one value and assign the results the label on the form.

    This is my code, but I am stuck without how to get the results and assign them to the label on the form.


    private void button1_Click(object sender, EventArgs e) 
            { 
     
                SqlConnection myConnection = new SqlConnection("Data Source=(local);Initial Catalog=Staff;Integrated Security=SSPI"); 
     
                try 
                { 
                    myConnection.Open(); 
                    SqlCommand myCommand = new SqlCommand("select * from Customers WHERE id = 1 ", myConnection); 
                    SqlDataReader myReader = myCommand.ExecuteReader(); 
     
                    //Code to assign the value returned by the querry to the label on the form 
     
                     
                } 
                finally 
                { 
                    myConnection.Close(); 
                } 
            }

    Thanks in advance.


    Thursday, January 15, 2009 7:30 AM

All replies

  •  this is easy solution -

            while (myReader.Read())  
            {  
                label.Text = (string)myReader[x];//x - column number  
            }  
            // Call Close when done reading.  
            myReader.Close();  
     

    SaltFish
    Salty and chilled, but always coded!
    Thursday, January 15, 2009 11:03 AM
  • I have done likewise, but I am getting an  arguement exception saying "Invalid value for key 'integrated security'.";

    Could it be that my connection string is not correct. Not to familiar with that..

    I am using Visual Studio 2008 and SQL Server 2008.


    Thursday, January 15, 2009 11:29 AM
  • There is missing character in your connection string -

    SqlConnection myConnection = new SqlConnection("Data Source=(local);Initial Catalog=Staff;Integrated Security=SSPI;"); 

    SaltFish

    Salty and chilled, but always coded!
    Thursday, January 15, 2009 11:56 AM