How to Display the Data in a Textbox Using C#

In this tutorial, I will teach you how to display the data in a textbox using c#. This method has the ability to retrieve the data in the database and display it in the textbox. It is very useful, especially when you want to retrieve specific data in the database. Hope this tutorial will help you to solve your current problem in programming.

Creating a Database

Create a database in the “PHPMyAdmin” and named it “tuts_dbperson”. After that, execute the following query to create a table in the database that you have created.
  1.  
  2. CREATE TABLE `tuts_dbperson`.`tblperson` ( `PersonID` INT NOT NULL AUTO_INCREMENT ,`Fullname` VARCHAR(90) NOT NULL , `Address` VARCHAR(90) NOT NULL , PRIMARY KEY(`PersonID`)) ENGINE = InnoDB;
Insert the data in the table.
  1. INSERT INTO `tblperson` (`PersonID`, `Fullname`, `Address`) VALUES
  2. (2, 'Janobe Sourcecode', 'Kabankalan City');

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application in c#. figure 1

Step 2

Add two textboxes, and two labels after that do the form just like shown below. figure 2

Step 3

Add MySQL.Data.dll as references.

Step 4

Press F7 to open the code editor. In the code editor, add a namespace to access MySQL libraries.
  1.  
  2. using MySql.Data.MySqlClient;

Step 5

Create a connection between c# and MySQL database and declare all the classes that are needed.
  1.  
  2. MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=tuts_dbperson;sslMode=none");
  3. MySqlDataAdapter da;
  4. MySqlCommand cmd;
  5. DataTable dt;
  6. string sql;

Step 6

Create a method for retrieving data in the database and display it on the textbox.
  1.  
  2. private void RetrieveSingleResult(string sql)
  3. {
  4. try
  5. {
  6. con.Open();
  7.  
  8. cmd = new MySqlCommand();
  9. da = new MySqlDataAdapter();
  10. dt = new DataTable();
  11. int maxrow;
  12.  
  13. cmd.Connection = con;
  14. cmd.CommandText = sql;
  15. da.SelectCommand = cmd;
  16. da.Fill(dt);
  17.  
  18. maxrow = dt.Rows.Count;
  19. if(maxrow > 0)
  20. {
  21. textBox1.Text = dt.Rows[0].Field<string>("Fullname");
  22. textBox2.Text = dt.Rows[0].Field<string>("Address");
  23. }
  24.  
  25. }
  26. catch(Exception ex)
  27. {
  28. MessageBox.Show(ex.Message);
  29. }
  30. finally
  31. {
  32. con.Close();
  33. da.Dispose();
  34. }
  35. }

Step 7

Write the following codes to display the data in the textbox in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. sql = "SELECT * FROM `tblperson` WHERE PersonID=2";
  5. RetrieveSingleResult(sql);
  6. }
The complete source code is included. You can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment