How to display TextBox/ComboBox value from database table?

VAer-4038 761 Reputation points
2021-01-03T21:13:42.947+00:00

There is a database table TableUser, and there are four fields: FirstName, LastName, Country, State. Actually, there is another field Username, which does not require user to provide, it is ENvironment.Name

When user submits his/her information, first three fields are required, and State is optional.

Now in another form, user wants to update his/her information (It is guaranteed that the user is in database).

Two parts of question:
How to display the record value back into TextBox/ComboBox?
When user updates his/her information, how to write the code to update information in database? It is same that first three fields are required and State is optional.

Thanks.

    private void ChildForm1_Load(object sender, EventArgs e)
           {


               OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString);
               Cn.Open();

 string query = "SELECT * from TableUser WHERE Username = '" + ENvironment.Name + "'";
 //It is guaranteed that there is one record

 TextboxFirstName.Text = FirstName from returned query; there is a value
 TextboxLastName.Text = LastName from returned query; there is a value

 ComboBoxCountry.Text = Country from returned query; there is a value
 ComboBoxState.Text = State from returned query; It may be missing/null


               Cn.Close();


           }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,860 questions
0 comments No comments
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-01-04T07:38:07.51+00:00

    Hi VAer-4038,
    For question1, you can try the following the code:

    using (OdbcConnection connection = new OdbcConnection())  
     {  
            connection.ConnectionString = "Your connectionString";  
            connection.Open();  
            OdbcCommand command = new OdbcCommand("SELECT * from TableUser WHERE Username = '" + ENvironment.Name + "'", connection );  
            // Execute the DataReader and access the data.  
            OdbcDataReader dr = command.ExecuteReader();  
            while (dr.Read())  
            {  
               TextboxFirstName.Text = dr["FirstName"].ToString();  
               TextboxLastName.Text = dr["LastName "].ToString();  
            }  
    }  
    

    For question2, you can use OdbcCommand.ExecuteNonQuery method to execute an SQL statement against the connection.
    And here is code example i this document you can refer to.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful