Getting data from MS Access database and display it in a listbox

后端 未结 7 858
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 06:37

How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.

 private void button3_Click(object sender, Even         


        
7条回答
  •  孤街浪徒
    2020-12-11 07:24

    If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label. First of all create any Access data base like here "PirFahimDataBase". Now in your Visual Studio go to the menu and do this

    1. Click Data
    2. Add New Data Base
    3. Click Next
    4. Click New Connection
    5. Now change the Data Source by clicking Change and select Microsoft Access data base files
    6. Click Browse for selecting your created data base

    Now in Button ClickEvent paste these code which will get data from data base and will show it in the label

    using System.Windows.Forms; //these two lines should be written before namespace at top of the program
    using System.Data.OleDb;
    
    private void button1_Click(object sender, EventArgs e)
        {        
          System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
         conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
        @"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
    
        try
         {
         conn.Open();
         MessageBox.Show("connected successfuly");
         OleDbDataReader reader  = null;  // This is OleDb Reader
       OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
         label1.Text= reader["TicketNo"].ToString();           
    
        }
    
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }    
     }//end of button click event
    

提交回复
热议问题