bind one combobox to another in wpf

时间:2015-07-28 22:15:41

标签: c# wpf winforms xaml combobox

I have three Combo boxes.I am fetching value of each combobox from the database and each combobox is dependent on the other. Currently, I am populating the combobox on the SelectionChanged() event. I am populating first combobox in the constructor of MainWindow.

So when I select a value from first combobox, the selectionchanged event is called. then second combox is poplulated. When I select a value from second combobox, third combobox is populated on selectionChanged event. After selecting value from third combo box, I am populating a data grid.

When I try and change value of first combobox after selecting value from third combobox, I get an error.

Object reference not set to an instance of an object.!

I am trying to bind the comboboxes to each other, but I cannot figure out a way to do that being new to wpf.

I have attached code of combobox for reference.

 public MainWindow()

 {
         InitializeComponent();
         Fill_Combo();
 }

   //adding values in first combo box 
  void Fill_Combo()
    {
        try
        {
            string query = "select column_name from table_name";               
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            OracleCommand command = new OracleCommand();
            command.Connection = conn;
            command.CommandText = query;
            OracleDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                String str = reader.GetString(0);
                //source_name is name of combobox1  
                source_name.Items.Add(str);
            }
            reader.Dispose();                               
        }
        catch (Exception e)
        {
            MessageBox.Show(e.StackTrace + " :: in fill_combo");
        }
    } 

   // adding value in second combo box based on value in first combobox 
   private void source_name_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {          
        string query = "select column from table where source_name='" + source_name.SelectedItem.ToString() + "'";

        try
        {
            OracleConnection connection = new OracleConnection(connectionString);
            connection.Open();
            OracleCommand command = new OracleCommand();
            command.Connection = connection;
            command.CommandText = query;
            OracleDataReader reader = command.ExecuteReader();
            //clearing previous values in combobox2
            //target_box is the name of second combo box
            target_box.Items.Clear();
            while (reader.Read())
            {
                String str = reader.GetString(0);
                //adding values in second combobox
                target_box.Items.Add(str);
            }

            reader.Dispose();                                            
            connection.Close();

        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.Message + "source_name namespace SelectionChangedEventArgs chanegs");
        }
    }


   private void target_box_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            if (target_box.SelectedItem.ToString() != null && target_box.SelectedItem.ToString() != "Target system")
            {                   
                string query = "select columnname from map_pair_attributes where source_name='" + source_name.SelectedItem.ToString() + "'"
                      + "and target_name = '" + target_box.SelectedItem.ToString() + "'";
                OracleConnection connection = new OracleConnection(connectionString);
                connection.Open();
                OracleCommand command = new OracleCommand();
                command.Connection = connection;
                command.CommandText = query;
                OracleDataReader reader = command.ExecuteReader();
                attribute_box.Items.Clear();
                while (reader.Read())
                {
                    String str = reader.GetString(0);
                    //attribute box is name of third combobox
                    attribute_box.Items.Add(str);
                }

                reader.Dispose();
                connection.Close();
                connection.Dispose();


            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("in target box selection changed!" + ex.StackTrace + ex.Message);
        }
    }        

        //atributebox is name of third combobox 
         private void attribute_box_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {               
           String query = "select column_name from table where source_name='" + source_name.SelectedItem.ToString() + "' and target_name ='" +
                target_box.SelectedItem.ToString() + "' and attribute_name = '" + attribute_box.SelectedItem.ToString() + "'";

            OracleConnection conn = new OracleConnection(connectionString);
            conn.Open();
            DataSet ds = new DataSet();
            OracleDataAdapter da = new OracleDataAdapter(query, conn);
            da.Fill(ds, "table_name");
            grid1.ItemsSource = ds.Tables["table_name"].DefaultView;
              conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("attribute box selection changed!" + ex.Message);

        }
    }

.XAML file

   <ComboBox x:Name="target_box" HorizontalAlignment="Left" Margin="179,49,0,0" VerticalAlignment="Top" Width="120" 
        IsEditable="true" IsReadOnly="True" Text="Target system" 
        Focusable="True" SelectionChanged="target_box_SelectionChanged" />
                <ComboBox x:Name="source_name" HorizontalAlignment="Left" Margin="19,49,0,0" VerticalAlignment="Top" Width="120" 
        IsEditable="true" IsReadOnly="True" Text="Source system" Focusable="True" SelectionChanged="source_name_SelectionChanged"/>
                <ComboBox x:Name="attribute_box" HorizontalAlignment="Left" Margin="363,49,0,0" VerticalAlignment="Top" Width="120"
        IsEditable="true" IsReadOnly="True" Text="Attribute" Focusable="True" SelectionChanged="attribute_box_SelectionChanged" />

Can someone please help me with this. I think binding can solve the problem, but I do not know how to bind the comboboxes.

Thanks!

1 个答案:

答案 0 :(得分:1)

When you select a new item in the lines = defaultdict(dict) with open("file_parse.txt") as f: for line in f: parts = line.split() key = tuple(parts[1:3]) # unique key with servername and datetime lines[key][parts[0]] = parts[3] lines[key]["servername"] = parts[1] lines[key]["datetime"] = parts[3] res = list(lines.values()) print(res) # [ # {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084445'}, # {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084440'}, # {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084450'} # ] , the ComboBox is first set to null.

Try adding in checks for ComboBox.SelectedItem = null in each event handler before trying you are calling ToString() on the object.

e.g.

ComboBox.SelectedItem

Then replace your ToString null checks

if(source_name.SelectedItem == null) return;

with

if (target_box.SelectedItem.ToString() != null