0

I'm new to C#. I thought I knew a bit of C# but clearly not.

I'm trying to communicate with an Arduino using a C# Windows Form via the serial communication, when the button3 is clicked, the Windows Form app will send a command, for the Arduino to send back the required data, for the Windows Form app to fill in the specified Textboxes, but I'm getting Error CS0103 The name 'tb' does not exist in the current context error.

I have tried all possible options provided but with no luck. This is the my code:

private void button3_Click(object sender, EventArgs e)
        {
            TextBox[] myTextBoxes = new TextBox[] { textBox9, textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16 };
            String[] myCommands = new String[] { "#TRMMH1\n", "#TRMMM1\n", "#TRMMH2\n", "#TRMMM2\n", "#TRMMH3\n", "#TRMMM3\n", "#TRMMH4\n", "#TRMMM4\n" };
            String inString;

            foreach (String co in myTextBoxes.SelectMany(tb => myCommands))
            {
                port.Write(co);
                inString = port.ReadLine();
                tb.Text = inString;
            }

I have tried to search Google and Stack Overflow, but I'm not sure what to search for.

OndiAluc
  • 27
  • 5
  • 1
    You do not have a textBox named "tb" on the designer half of your Programm or further up in the class code. You need to use or change the actuall name of the textbox - which represents the variable name. – Christopher Aug 18 '21 at 10:19

1 Answers1

0

You have two Size 8 arrays. You can not process two arrays in that way with a foreach - you need a for loop so you can use the running variable for both

TextBox[] myTextBoxes = new TextBox[] { textBox9, textBox10, textBox11, textBox12, textBox13, textBox14, textBox15, textBox16 };
String[] myCommands = new String[] { "#TRMMH1\n", "#TRMMM1\n", "#TRMMH2\n", "#TRMMM2\n", "#TRMMH3\n", "#TRMMM3\n", "#TRMMH4\n", "#TRMMM4\n" };

for(int i=0; i<myTextBoxes.Lenght && i<myCommands.Lenght; i++){
    TextBox curTB = myTextBoxes[i];
    String curCMD = myCommands[i];
   
    port.Write(curCMD);
    string temp = port.ReadLine();
    curTB.Text = temp;
}

I did not run this code, so off-by-one or syntax errors are to be expected.

Christopher
  • 9,634
  • 2
  • 17
  • 31
  • Thank you so much Christopher! This is exactly what I was trying to accomplish with the _foreach_ loop. – OndiAluc Aug 18 '21 at 23:08