Posted by: rsusanto on: June 24, 2010
In this part i will demonstrate use of Binding Source in purpose to filter data that linked with another data.
So lets go to the case learning.
The case is about a simple form to choose singer due their genre.
In this case i have 2 control in my form. The 1st Combo Box which contain datas about genres of music
date then 2nd Combo Box which contain datas about singer/band.
Im gonna use List for the Genre with this domain POP, ROCK, JAZZ
And for the singer i will use SQL Server 2000 with SQL Server Management Studio Express. I named the table singer :

So we must filter the data in the 2nd Combo Box due selected data in 1st Combo Box to match the singer to their genre.
This is how the form looks, quiet simple right
:

Now we will step into the code.
Type this on the top of using System.Data.SqlClient;


private SqlConnection buildConn()
{
string strConn = @"Data Source = .\SQLEXPRESS;
Integrated Security = SSPI;
Initial Catalog = confuseisme;";
return new SqlConnection(strConn);
}private void fillCmbGenre()
{
lststrGenre.Add("POP");
lststrGenre.Add("JAZZ");
lststrGenre.Add("ROCK");
cmbGenre.DataSource = lststrGenre;
}Use lststrGenre.Add(String param) function to add domain data. Then set lststrGenre as cmbGenre.DataSource value. So we dont dont to have loop then cmbGenre.Items.Add(string Param).
private int fillDtSinger()
{
int intResp = -1;
try
{
if (conn.State.ToString() != "Open")
conn.Open();string strCmd = "SELECT * FROM T_Singer ORDER BY genre,singer;";
cmd = new SqlCommand(strCmd, conn);
da.SelectCommand = cmd;
da.Fill(dtSinger);
}
catch (SqlException e)
{
intResp = e.Number;
}
finally
{
cmd.Dispose();
da.Dispose();
conn.Close();
}
return intResp;
}
private void fillCmbSinger()
{
bs.RemoveFilter();
bs.Filter = "genre = '" + cmbGenre.Text + "'";
cmbSinger.Items.Clear();
foreach (DataRowView drv in bs)
{
cmbSinger.Items.Add(drv[1].ToString());
}
}
We wan filter function working whenever we select another Genre so we put this
private void cmbGenre_SelectedIndexChanged(object sender, EventArgs e)
{
fillCmbSinger();
}
public F_Blog_BindingSource()
{
InitializeComponent();
conn = buildConn();
dtSinger = new DataTable();
lststrGenre = new List();
da = new SqlDataAdapter();
bs = new BindingSource();
dtSinger = new DataTable();
}May this post works and benefits you, let me know if you have some question about this case. And it will be nice if we you give me some advice, because seriously this is my first blog post. After all thanks
Credit for msdn.microsoft.com for definitions