Binding to a list control is one of the most common task. I think most of the .NET list controls has a DataSource property in which accepts reference to any datasource(IList).
In our example I used MSACCESS for our backend database for simplicity. This will be our example data for the rest of the databinding samples!
Sample screenshot of the application!
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add providerName="System.Data.OleDb"
name="MyConnectionString"
connectionString=
"Provider= Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\SampleDB.accdb;User Id=admin;Password=;"/>
</connectionStrings>
</configuration>
To use ConfigurationManager, please add System.Configuration to your references.using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace DataBinding
{
public class clsGetData
{
public DataTable getProducts()
{
DataSet ds = new DataSet();
using(OleDbConnection cn = new OleDbConnection
(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM tblSampleProducts", cn))
{
using (OleDbDataAdapter adptr = new OleDbDataAdapter(cmd))
{
adptr.Fill(ds, "tblProducts");
}
}
}
return ds.Tables["tblProducts"];
}
}
}
clsInstance.cs < i created this class for single instance of clsGetData
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace DataBinding
{
public class clsInstance
{
private static readonly clsGetData getData = new clsGetData();
public static clsGetData Products
{
get { return getData; }
}
}
}
Form1.cs
namespace DataBinding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnBind_Click(object sender, EventArgs e)
{
this.lstProducts.DataSource = clsInstance.Products.getProducts();
this.lstProducts.ValueMember = "ProductID";
this.lstProducts.DisplayMember = "ProductName";
}
private void btnBindDataView_Click(object sender, EventArgs e)
{
DataTable dt = clsInstance.Products.getProducts();
dt.DefaultView.RowFilter = "ProductPrice < 1000";
this.lstProducts.DataSource = dt;
this.lstProducts.ValueMember = "ProductID";
this.lstProducts.DisplayMember = "ProductName";
}
}
}






0 comments:
Post a Comment