Search code examples
c#.netwindows-forms-designer

Is it possible to implement a value change in a textbox depending on the change of values in two comboboxes?


I need advice on Windows Forms. I need to make the textbox change the value depending on which values I choose in the two comboboxes.

For example. I have a combobox with a choice of machines(1,2,3,4 etc.) and a combobox with a choice of products(a,b,c,d etc.). I need a textbox with the number of products produced(100,200,300,400 etc.) to change based on the choice of two values of comboboxes. This value of the textbox should depend on the machine and the product values. The problem is that I don't know how to solve the fact that product "a" can be combined with different machines, and these are different textbox values.

I managed to make the value in the textbox change when I selected one combobox. But there are no ideas at all to link one textbox and two comboboxes. Thank you!


Solution

  • No exactly know what your issue is.Here is a full code example of how to link two comboboxes to update a textbox value in Windows Forms.You can separate the SelectedIndexChanged event based on what you want.

    public partial class Form1 : Form
    {
        Dictionary<Tuple<string, string>, int> machineProductValues;
    
        public Form1()
        {
            InitializeComponent();
    
            machineProductValues = new Dictionary<Tuple<string, string>, int>()
            {
                {new Tuple<string, string>("Machine 1", "Product A"), 100},
                {new Tuple<string, string>("Machine 1", "Product B"), 200},
                {new Tuple<string, string>("Machine 2", "Product A"), 300},
                {new Tuple<string, string>("Machine 2", "Product B"), 400}
            };
    
            // Populate comboboxes 
            machineCombo.Items.Add("Machine 1");
            machineCombo.Items.Add("Machine 2");
    
            productCombo.Items.Add("Product A");
            productCombo.Items.Add("Product B");
    
            // Subscribe to events
            machineCombo.SelectedIndexChanged += Combo_SelectedIndexChanged;
            productCombo.SelectedIndexChanged += Combo_SelectedIndexChanged;
        }
    
        private void Combo_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateOutputValue();
        }
    
        private void UpdateOutputValue()
        {
            string machine = machineCombo.SelectedItem.ToString();
            string product = productCombo.SelectedItem.ToString();
    
            Tuple<string, string> key = new Tuple<string, string>(machine, product);
    
            if (machineProductValues.ContainsKey(key))
            {
                outputTextBox.Text = machineProductValues[key].ToString();
            }
        }
    }