Display Database Records in ListView using C#

In this tutorial, I will teach you how to create a program that will load records to a combobox from a SQL Server 2008 database using c#. This will be very helpful in making your systems or thesis. So, now let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application. 2. Add only one ListView in your Form. In its Properties, have its Full Row Select and GridLines to True, the View into Detals, and Add labels such as ID, Username, and Password into the Column Names. design 3. We will first create a database named sampleDatabase using the SQL Server 2008 database. Create a table named tblLogin and have an entity of ID as int datatype, and username and password having varchar datatype. design Then put records inside the table and we will retrieve and retrieve this later in our ListView. design 4. Now, let's do the coding. We will first import the SQL namespace as we will have the SQL database.
  1. using System.Data.SqlClient;
Have the connection string of your sql database, the command, connection, and the data reader.
  1. public SqlCommand cm = new SqlCommand();
  2. public SqlConnection cn = new SqlConnection();
  3. public SqlDataReader dr;
  4.  
  5. public string constring = @"Data Source=don-PC;Initial Catalog=sampleDatabase;Integrated Security=True"
Create a function named viewList() that will load the records from the database to the combobox. Use the table named tblLogin.
  1. void viewList()
  2. {
  3.  
  4. listView1.Items.Clear();
  5. string sql = "select * from tblLogin";
  6. cm = new SqlCommand(sql, cn);
  7. dr = cm.ExecuteReader();
  8. while (dr.Read())
  9. {
  10.  
  11. list = listView1.Items.Add(dr.GetValue(0).ToString());
  12. list.SubItems.Add(dr.GetValue(2).ToString());
  13. list.SubItems.Add(dr.GetValue(1).ToString());
  14.  
  15.  
  16. }
  17. dr.Close();
  18. }
And then call this viewList() function inside the Form_Load with the connection of your database to open it. .
  1. private void Form1_Load(object sender, EventArgs e)
  2. {
  3. cn = new SqlConnection(constring);
  4. cn.Open();
  5. viewList();
  6. }
Output: output For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment