Home > Blockchain >  Ho do I edit Textbox of Form1 through another class in c#
Ho do I edit Textbox of Form1 through another class in c#

Time:06-09

I have Form1.Designer.cs and another class MyClass. MyClass.cs simply contains methods for API actions. In MyClass.cs, using the API I try to get the number of devices connected to my PC and store it in the list. Now I want to display that list in the ComboTexbox in Form1.Designer.cs

When I write the method in Form1.cs of course it works perfectly fine. Code in Form1.cs

 private void button1_Click(object sender, EventArgs e)
        {
            MyClass.Connect();
            MyClass.GetConnted_Device();
         }

code in MyClass

public string[] DriverNameList;
public List<string> DeviceNameList = new List<string>();
public int device_length = 0;

public void GetConnted_Device()
        {   
            " ommitted code to get the connected device using API"
            // Get all the device and stored them in DriverNamelist 

            DeviceNameList = DriverNameList.ToList();
            device_length = DeviceNameList.Count;
          }

I tried the following method but it seems I have to create a separate method for this https://stackoverflow.com/a/16877500/19059210

CodePudding user response:

You don't. The only object that should be making changes to a form is that form. The methods in that class should return data. The form can then call a method, get the data and update its own control(s) with that data. Alternatively, the method could remain void and then the form could call the method and then get the data from the appropriate field of that class. Either way, it's the form getting the data from the class instance and then updating its own UI. That other class should not have to know anything about what's using it.

By the way, public members should be properties, not fields.

CodePudding user response:

DeviceNameList.ForEach(x => comboBoxTextBox.Items.Add(x));

  • Related