C# tutorial-Database support: DataAdapter and DataSet objects |
|||||||||||||||||||||||||||
DataAdapter and DataSet objectsDataAdapter 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)
namespace CWindowGUI { public partial class ImageView : Form
{ public ImageView() { InitializeComponent(); displaydata(); //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 cn.Open();
//create DataAdapter object ad = new OleDbDataAdapter("Select * From tblimages", cn); //Fill data to DataSet object ad.Fill(ds, "tblimages"); //clear listview Lstimages.Clear(); //add columns addcolumns(); 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()); ++p;} //close the connection cn.Close(); }
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); item.SubItems.Add(path); Lstimages.Items.Add(item);
}
private void Lstimages_SelectedIndexChanged(object sender, EventArgs e) { ListView.SelectedListViewItemCollection sel = Lstimages.SelectedItems; foreach (ListViewItem item in sel) { //view selected image pictureBox1.Image=Image.FromFile(item.SubItems[1].Text); } } }
}
|
|||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||