我有一個 ContextMenuStrip 叫做:DGVContextStrip它在用戶右鍵單擊我的 datagridview 時顯示。
該 MenuStrip 包含一個名為的專案AddUpgradeTagToolStripMenuItem
,其中包含子專案(dropdownitems),這些子專案都在其名稱中以數字命名。例如:Add1ToolStripMenuItem, Add2ToolStripMenuItem, Add3ToolStripMenuItem.... 依此類推,直到Add25ToolStripMenuItem。
當用戶在 Datagridview 上右鍵單擊時,我想檢查一個單元格是否包含數字“1”,然后它是否確實使 Add1ToolStripItem.checked = true
我想我會遍歷數字 1 到 25,并在每個回圈中檢查單元格是否包含 1,如果為真,則更改選單項的選中值。就像是...
For i = 1 to 25
If DataGridView1.SelectedRows(0).Cells("Text_Field").Value.ToString.Contains(i) then
CType("Add" & i & "ToolStripMenuItem", ToolStripMenuItem).Checked = True
Next
但這不起作用,我在網上看到了使用 control.find 方法的示例,但我無法使用它。例如
Dim ControlName As String = "Add" & i & "ToolStripMenuItem"
CType(Me.Controls.Find(ControlName, True), ToolStripMenuItem).Checked = True
任何想法我如何讓它作業?我意識到我可以使用 25 個 if then else 陳述句,但我有點想讓代碼更簡潔。
uj5u.com熱心網友回復:
該ToolStripItem不是尋找一個在控制Control.ControlCollection。您需要搜索ToolStripItemCollection它所屬的位置。
就像Control.ControlCollection.Find方法一樣,該ToolStripItemCollection.Find方法可以對專案執行深度搜索。
您的案例示例:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
Dim tsmi = yourContextMenuStrip.Items.
Find(itemName, True).
OfType(Of ToolStripMenuItem).
FirstOrDefault()
If tsmi IsNot Nothing Then
tsmi.Checked = True
End If
或者,如果您已經知道目標專案是AddUpgradeTagToolStripMenuItem下拉專案之一,那么您可以執行以下操作:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
Dim tsmi = DirectCast(AddUpgradeTagToolStripMenuItem, ToolStripMenuItem).
DropDownItems.OfType(Of ToolStripMenuItem).
FirstOrDefault(Function(x) x.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase))
If tsmi IsNot Nothing Then
tsmi.Checked = True
End If
如果您只需要檢查集合中的一項:
Dim itemName As String = $"Add{i}ToolStripMenuItem"
For Each tsmi In DirectCast(AddUpgradeTagToolStripMenuItem, ToolStripMenuItem).
DropDownItems.OfType(Of ToolStripMenuItem)
If tsmi.Name.Equals(itemName, StringComparison.OrdinalIgnoreCase) Then
tsmi.Checked = True
Else
tsmi.Checked = False
End If
Next
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361784.html
