簡體   English   中英

菜鳥與事件; 擊中F5后引起動作

[英]Rookie With Events; Causing Action after hitting F5

因此,是的,我對於創建自己的自定義事件還很陌生。 當我將控件放在窗體上時,我可以做一些基礎工作,但是這要復雜一些。 我有一個讀取.TSV的應用程序,該應用程序根據其“讀取”的對象數填充控件。 因此,例如:我有一個包含10個人對象的文件,我的代碼用每個人的控件填充了一個表單。 簡單的東西!

現在,假設我有一個帶有以下各項的組合框:“活着”,“已故”,“未出生”。 在此旁邊,我有一個年齡文本框。 現在,最初,此文本框未啟用,因為ComboBox的默認值為“ Unborn”。 但是可以說,當用戶選擇“活着”時,我希望該文本框啟用,以便可以輸入年齡。

很明顯,從我問這個問題和這個問題的標題,我不知道該怎么做。 我不是很了解事件,而是通過示例學習,但是MSDN示例並沒有完全消除它。

任何幫助(尤其是很棒的分步指南)將不勝感激。

根據我從注釋中收集的信息,您希望將事件添加到在運行時創建的表單對象。 對對象使用AddHandler命令。 效果:

AddHandler NameOfFormObject.TypeOfAction, AddressOf HowToHandle

Private Sub HowToHandle(ByVal sender as System.Object, ByVal e As System.EventArgs)
   DropDownMenu.enabled = True
End Sub

這樣,您將能夠修改運行時創建的對象的事件。 在您的情況下,聽起來您將要使用Josaph建議的操作,並最終將所提供的兩種解決方案都納入其中,例如

AddHandler ComboBox1.SelectedIndexChanged, AddressOf HowToHandle

Private Sub HowToHandle(ByVal sender as System.Object, ByVal e As System.EventArgs)

    If DirectCast(sender, ComboBox).SelectedIndex = 0 'Alive 
        DirectCast(DirectCast(sender, ComboBox).Tag, TextBox).enabled = True
    Else
        DirectCast(DirectCast(sender, ComboBox).Tag, TextBox).enabled = False
    End If
End Sub

您將需要使用ComboBox_SelectedIndexChanged()事件來捕獲組合框項目已被更改。 此時,您將需要檢查以查看選擇了哪個組合框項目,並決定是否應啟用TextBox。 這是一個例子。 注意:此示例假定“ Alive”是組合框中索引為0的第一項。


    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If ComboBox1.SelectedIndex = 0 Then 'Alive 
            TextBox1.Enabled = True
        Else
            TextBox1.Enabled = False
        End If
    End Sub

動態生成組合框並添加處理程序。

Dim cmb as New ComboBox
AddHandler cmb.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
Me.Controls.Add(cmb)

我想您將擁有10個組合框...以同樣的方式,您將擁有10個文本框。

在這種情況下...一旦以AndyPerfect和Joseph身份附加並處理了該事件...,就需要使用該方法編寫一些代碼,以了解需要啟用/禁用哪些文本框。

首先,您需要知道哪個組合框觸發了該事件:這是使用“ sender”參數完成的。 ctype(sender, Combobox)訪問ComboBox的方法和屬性。

一旦知道了哪個組合,就需要激活/停用正確的文本框。 為此,您需要在創建組合框時在組合框的“ TAG”屬性中添加對文本框的引用。

Dim txt as new TextBox
Dim cmb as new ComboBox
cmb.Tag = txt

然后...簡單使用:

ctype(ctype(sender, Combobox).Tag, TextBox).Enable = true

這就是我最終編寫它的方式。 我感謝所有的幫助! 謝謝!

    If DirectCast(sender, ComboBox).SelectedIndex = 2 Then
        DirectCast(Me.Controls.Item(DirectCast(sender, ComboBox).Tag), TextBox).Enabled = True
    Else
        DirectCast(Me.Controls.Item(DirectCast(sender, ComboBox).Tag), TextBox).Enabled = False
    End If

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM