0

我需要使用 MainWindow 页面中保存的另一个组合框中包含的所选名称的地址详细信息填充 page1 中的组合框。我已经尝试了下面的代码,但 MainWindow 中的组合框名称无法识别。

主窗口:

private void displayParts()
    {
        try
        {
            sc.Open();
            string Query = "select * from Parts";
            SqlCommand createCommand = new SqlCommand(Query, sc);
            SqlDataReader dr = createCommand.ExecuteReader();
            while (dr.Read())
            {
                string Name = dr.GetString(1);

                cbParts.Items.Add(Name);//Displaying a list in the Combo Box
            }
            sc.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

第 1 页:

 private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
     {            
       string constring = "Data Source=.;Initial Catalog=**.MDF;Integrated Security=True";
       DataContext=MainWindow.
         string Query = "select * from Partners where Name='" + cbParts.SelectedItem.ToString() + "' ;";
         SqlConnection conDataBase = new SqlConnection(constring);
         SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
         SqlDataReader myReader;

         try
         {


             sc.Open();
             myReader = cmdDataBase.ExecuteReader();
             if (myReader.Read())
             {
                 txtPartner.Text = myReader["Name"].ToString();
             }

             myReader.Close();


             sc.Close();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
4

1 回答 1

0
// may need to cast this to your MainWindow's type
var mainWindow = Application.Current.MainWindow; 

//...

mainWindow.cbParts.Items.Add(Name);

此外,您可以将组合框绑定到ObservableCollection属性,并将项目添加到集合中。

于 2013-08-19T19:26:13.487 回答