从组合框获取值绑定到dataTable

时间:2015-05-08 13:23:24

标签: c# wpf combobox

我有一个绑定到数据表的组合框。我希望能够获取所选项目中的DisplayMemberPath和SelectedValuePath项目的值。这就是我所拥有的:

private void CboCustomerList_DoWork(object sender, DoWorkEventArgs e)
{

    string connectionString = Settings.Default.ProdConnectionString;
    SqlConnection connection = new SqlConnection(connectionString);

    SqlCommand SqlCmd = new SqlCommand();
    SqlCmd.CommandType = CommandType.StoredProcedure;
    SqlCmd.CommandText = "sp_GetItemIds";
    SqlCmd.Parameters.Add("@customer", SqlDbType.NVarChar).Value = CboCustomerList.SelectedValue.ToString().Trim();
    SqlCmd.Connection = connection;
    SqlDataAdapter sqlDa = new SqlDataAdapter();
    sqlDa.SelectCommand = SqlCmd;
    DataSet ds = new DataSet();


    try
    {
        sqlDa.Fill(ds, "ITEMS");
        DataRow nRow = ds.Tables["ITEMS"].NewRow();
        nRow["EXTITEM"] = string.Empty;
        nRow["ITEMID"] = "0";
        ds.Tables["ITEMS"].Rows.InsertAt(nRow, 0);

        //Binding the data to the combobox.
        CboItemId.DataContext = ds.Tables["ITEMS"].DefaultView;
        connection.Close();

        CboItemId.DisplayMemberPath =
            ds.Tables["ITEMS"].Columns["EXTITEM"].ToString();

        CboItemId.SelectedValuePath =
            ds.Tables["ITEMS"].Columns["ITEMID"].ToString();


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        connection.Close();
        SqlCmd.Dispose();
    }

}

2 个答案:

答案 0 :(得分:0)

你可以在选择更改事件

上获得它
  private void CboItemId_SelectionChanged(object sender, SelectionChangedEventArgs e) 
  { 
      string item = CboItemId.SelectedItem.ToString();
      string val = CboItemId.SelectedValue.ToString();
  }

答案 1 :(得分:-1)

你现在可能已经知道了(3年前问过),但是在将数据绑定到组合框之前,你必须设置显示成员和值成员。