C# tutorial-Database support: DataAdapter and DataSet objects

DataAdapter and DataSet objects

DataAdapter object can connect to a database through a Connection object. It has a method (Fill) that can fill data to a DataSet object. DataSet object stores tables and relationships among those tables in memory temporarily.

Example: Retrieve data from tblimages and populate the data to a listview control(Lstimages)

Retreive database


namespace CWindowGUI


    public partial class ImageView : Form



        public ImageView()




  //select the first item of the listview

            Lstimages.Items[0].Selected = true;



private void displaydata(){

        DataSet ds=new DataSet();


        OleDbDataAdapter ad;


        //Start connection

        OleDbConnection cn=new OleDbConnection();

       //Set connection string

        cn.ConnectionString="Provider=Microsoft.Jet.Oledb.4.0; Data Source="+ Application.StartupPath+ "\\dbimages.mdb";

        //open the connection



        //create DataAdapter object

        ad = new OleDbDataAdapter("Select * From tblimages", cn);

        //Fill data to DataSet object

        ad.Fill(ds, "tblimages");

        //clear listview


        //add columns


        int p=0;

        //populate the listview

        foreach (DataRow row in ds.Tables[0].Rows){

            addDataToList(p, row[ds.Tables[0].Columns[0]].ToString(), row[ds.Tables[0].Columns[1]].ToString());


        //close the connection




private void addcolumns(){

        Lstimages.View = View.Details;

        //disable multi selection and enable full row selection

        Lstimages.MultiSelect = false;

        Lstimages.FullRowSelect = true;

        //add 2 columns to listview--ID and Path


        Lstimages.Columns.Add("ID", 30, HorizontalAlignment.Center);

        Lstimages.Columns.Add("Path", 300, HorizontalAlignment.Center);





private void addDataToList(int index , string  id, string path)




    ListViewItem item = new ListViewItem(id,index);









private void Lstimages_SelectedIndexChanged(object sender, EventArgs e)


    ListView.SelectedListViewItemCollection sel = Lstimages.SelectedItems;

    foreach (ListViewItem item in sel)


        //view selected image








This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.