Check if the drop-down list contains a dynamically added item

I am adding existing COM ports available on the system to the drop-down list. So far I have this:

private void Form1_Load(object sender, EventArgs e) { foreach (string port in System.IO.Ports.SerialPort.GetPortNames()) { ToolStripMenuItem t = new ToolStripMenuItem(); t.Text = port; t.Checked = port == notifier.COMPort; t.Click += t_Click; setPortToolStripMenuItem.DropDownItems.Add(t); } } 

This works when adding ports initially, however I want to check again for COM ports that have been added or removed before the user clicks on my drop-down box to display the ports.

I see that I can use setPortToolStripMenuItem.DropDOwnItems.ContainsKey() , but I have no idea what keys it uses when I add them.

This does not work:

 private void setPortToolStripMenuItem_DropDownOpening(object sender, EventArgs e) { string[] ports = System.IO.Ports.SerialPort.GetPortNames(); foreach (string s in ports) { if (!setPortToolStripMenuItem.DropDownItems.ContainsKey(s)) { ToolStripMenuItem t = new ToolStripMenuItem(); t.Text = s; t.Checked = s == notifier.COMPort; t.Click += t_Click; setPortToolStripMenuItem.DropDownItems.Add(t); } } } 

Is it possible to indicate which key it uses when I add an item, or is there another way to check for existing items?

+4
source share
2 answers

Running ContainsKey

Try setting Name -property to ToolStripMenuItem :

 ToolStripMenuItem t = new ToolStripMenuItem(); t.Name = port; // Set the name of the ToolStripMenuItem to the port. t.Text = port; t.Checked = port == notifier.COMPort; t.Click += t_Click; setPortToolStripMenuItem.DropDownItems.Add(t); 

Then ContainsKey(s) will work:

 foreach (string s in ports) { if (!setPortToolStripMenuItem.DropDownItems.ContainsKey(s)) { //.... } } 

Doing this with Linq

You can also use Linq to get all ports that are not in the ToolStrip:

 string[] ports = System.IO.Ports.SerialPort.GetPortNames(); var existingPorts = setPortToolStripMenuItem.DropDownItems .OfType<ToolStripMenuItem>() .Select(t => t.Text); // Or t.Name if you set that. var portsToAdd = ports.Except(existingPorts); 

Now all ports that are not in the drop-down list will be in portsToAdd , so you can add them without checking anymore.

Read more about Linq Except here .

+5
source

Yes, you can check it out -

 bool alreadyExist = setPortToolStripMenuItem.DropDownItems .OfType<ToolStripItem>() .Any(item => item.Text.Equals(s)); 
+1
source

Source: https://habr.com/ru/post/1497501/


All Articles