Attach a SQL database to ComboBox.ItemSource (WPF)

前端 未结 2 505
轮回少年
轮回少年 2021-01-16 17:09

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

2条回答
  •  礼貌的吻别
    2021-01-16 17:34

    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();
    
        
    
    
    
    
    
    
    
    

    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();
      }
    
    }
    

提交回复
热议问题