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
you can try like this ..you can bind the item source property of combobox like this below..
ItemsSource="{Binding}"
EDIT:
Connection string :
You can add in control event or class but it should be in wpf application window.
If you create new application in visual studio or visual c# or whatever it creates window1.xaml. you need to add connection string basically in class or event in that window1.xaml not in app.config or app.xaml.
connection string define in class:
Here is example by creating a class (its sql connector instead of OleDb which i showed in 1st one):
public class ConnectionHelper
{
public static SqlConnection GetConnection()
{
string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionStr);
return conn;
}
}
and you can use this class in your methods:
SqlConnection conn = ConnectionHelper.GetConnection();
<Window
.......
Loaded="OnLoad"
>
<Grid>
<ComboBox Height="18" SelectionChanged="cmbCategory_SelectionChanged"
ItemsSource="{Binding}"
HorizontalAlignment="Right" Margin="0,92,17,0" Name="cmbCategory"
VerticalAlignment="Top" Width="176"
BorderBrush="#FFFFFFFF" SelectedIndex="0"/>
</Grid>
</Window>
on load function u can assign values to combobox
private void OnLoad(object sender, System.EventArgs e)
{
ListCategories();
}
private void ListCategories()
{
sqlCon = new SqlConnection();
sqlCon.ConnectionString = Common.GetConnectionString();
cmd = new SqlCommand();
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Categories";
sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = cmd;
ds = new DataSet();
try
{
sqlDa.Fill(ds, "Category");
DataRow nRow = ds.Tables["Category"].NewRow();
nRow["CategoryName"] = "List All";
nRow["CategoryID"] = "0";
ds.Tables["Category"].Rows.InsertAt(nRow, 0);
//Binding the data to the combobox.
cmbCategory.DataContext = ds.Tables["Category"].DefaultView;
//To display category name (DisplayMember in Visual Studio 2005)
cmbCategory.DisplayMemberPath =
ds.Tables["Category"].Columns["CategoryName"].ToString();
//To store the ID as hidden (ValueMember in Visual Studio 2005)
cmbCategory.SelectedValuePath =
ds.Tables["Category"].Columns["CategoryID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while loading categories.");
}
finally
{
sqlDa.Dispose();
cmd.Dispose();
sqlCon.Dispose();
}
}
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. :)