I want to know how can I assign a SQL Server database to ItemSource property of a ComboBox (in a WPF app). I assigned the data source to the project but do
If someone else lands up here(like I did), here is the improved version of pratap k's code. Just pass 6 parameters to this method and it will fill your comboBox.
combobox - Name of the comboBox you want to fill
query - You query to fetch the data from the database
defaultValue - The default value you want to set to the comboBox
itemText - This the data you want to show in the list box. This is the name of the column of the DB and is in your SELECT query.
itemValue - This is the value you want to associate to the items of the combobox. This is also a column in your SELECT query and is the name of a column in your db. (If you don't need it, remove it from the code and the parameter too.
Also, you can pass these to values (DisplayMemberPath and SelectedValuePath) in your XAML code.
public bool fillComboBox(string connectionString, System.Windows.Controls.ComboBox combobox, string query, string defaultValue, string itemText, string itemValue)
{
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sqladp = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
using (SqlConnection _sqlconTeam = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionString].ConnectionString))
{
sqlcmd.Connection = _sqlconTeam;
sqlcmd.CommandType = CommandType.Text;
sqlcmd.CommandText = query;
_sqlconTeam.Open();
sqladp.SelectCommand = sqlcmd;
sqladp.Fill(ds, "defaultTable");
DataRow nRow = ds.Tables["defaultTable"].NewRow();
nRow[itemText] = defaultValue;
nRow[itemValue] = "-1";
ds.Tables["defaultTable"].Rows.InsertAt(nRow, 0);
combobox.DataContext = ds.Tables["defaultTable"].DefaultView;
combobox.DisplayMemberPath = ds.Tables["defaultTable"].Columns[0].ToString();
combobox.SelectedValuePath = ds.Tables["defaultTable"].Columns[1].ToString();
}
return true;
}
catch (Exception expmsg)
{
return false;
}
finally
{
sqladp.Dispose();
sqlcmd.Dispose();
}
}
Thanks pratap k. :)