我需要在page1中填充一个组合框,其中包含在MainWindow页面中保存的另一个组合框中包含的所选名称的地址详细信息。我已经尝试过以下代码,但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);
}
}
答案 0 :(得分:0)
// may need to cast this to your MainWindow's type
var mainWindow = Application.Current.MainWindow;
//...
mainWindow.cbParts.Items.Add(Name);
此外,您可以将组合框绑定到ObservableCollection
属性,并将项目添加到集合中。