Fill data from Database to ListBox : Data Bind ListBox : Database C# Source Code


Custom Search

C# Source Code » Database » Data Bind ListBox »

 

Fill data from Database to ListBox








    
 


using System;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

public class Form1 : System.Windows.Forms.Form {
    SqlConnection cn = new SqlConnection("data source=.;database=biblio;uid=admin;pwd=pw");
    SqlDataAdapter da = new SqlDataAdapter();
    string strSQL = "Select Title, PubID from Titles";
    SqlCommand cmd;
    SqlDataReader Dr;

    System.Windows.Forms.Button Button1 = new System.Windows.Forms.Button();
    System.Windows.Forms.ListBox ListBox1  = new System.Windows.Forms.ListBox();
    System.Windows.Forms.TextBox TextBox1  = new System.Windows.Forms.TextBox();

    public Form1() {
        cmd = new SqlCommand(strSQL, cn);
        this.SuspendLayout();

        this.Button1.Location = new System.Drawing.Point(136, 248);
        this.Button1.Size = new System.Drawing.Size(144, 32);
        this.Button1.Text = "Get Data";
        this.Button1.Click += new System.EventHandler(this.Button1_Click);

        this.ListBox1.Location = new System.Drawing.Point(48, 64);
        this.ListBox1.Size = new System.Drawing.Size(312, 160);

        this.TextBox1.Location = new System.Drawing.Point(48, 24);
        this.TextBox1.Size = new System.Drawing.Size(328, 20);
        this.TextBox1.Text = "Hit";

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(408, 293);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.Button1,
                                                                          this.ListBox1,
                                                                          this.TextBox1});
        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }

    private void Button1_Click(object sender, System.EventArgs e) {
        cn.Open(); 
        cmd.CommandText = strSQL + "'" + TextBox1.Text + "%'";
        Dr = cmd.ExecuteReader();
        ListBox1.Items.Clear(); 
        ListBox1.BeginUpdate();  

        while (Dr.Read()){
            ListBox1.Items.Add(Dr.GetString(0) + " - " + Dr.GetInt32(1).ToString());
        }

        ListBox1.EndUpdate();  

        Dr.Close();  

    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Database
» Data Bind ListBox