1

以下は、VisualBasicでオブジェクトを作成するために使用しているコードです。

    For indexCounter As Integer = 1 To TotalParticipants Step 1

        participantClock = New Label
        participantClock.Size = New Size(100, 20)
        participantClock.Name = "participantClock" & indexCounter
        participantClock.Location = New Point(139, (5 + ((indexCounter - 1) * 26)))
        participantClock.BorderStyle = BorderStyle.Fixed3D
        participantClock.TextAlign = ContentAlignment.MiddleRight
        CenterPanel.Controls.Add(participantClock)

        participantStop = New Button
        participantStop.Size = New Size(58, 20)
        participantStop.Location = New Point(245, (5 + ((indexCounter - 1) * 26)))
        participantStop.BackColor = Color.Red
        participantStop.ForeColor = Color.White
        participantStop.Font = New Font(participantStop.Font, FontStyle.Bold)
        participantStop.Text = "Stop"
        CenterPanel.Controls.Add(participantStop)

        participantTimer = New Timer
        participantTimer.Start()
        participantTimer.Enabled = True
        participantTimer.Interval = 1

        participantStopwatch = New Stopwatch
        participantStopwatch.Start()
Next

ラベル、ボタン、タイマー、ストップウォッチを作成しています。(沈没感はありますが、時間を数えているのでタイマーとストップウォッチの両方は必要ありません。)

私がやりたいのは、ラベルを作成し、そのラベルのテキストをストップウォッチからの値に設定することです。作成されるボタンは、そのストップウォッチを停止します。

私が抱えている問題は、ストップウォッチがまだ作成されていないため、名前でストップウォッチを呼び出すことができず、VBがそれにヒッシーフィットを投げかけることです。(結局、それは実際には宣言されていませんでした。)

したがって、問題は、最近動的に作成されたコントロールをどのように呼び出し、そのコントロールを使用してイベントを割り当てるかということです。それが不可能な場合は、フォームをダンプして、代わりに30個のストップウォッチの作成をやり直してもかまいません(ただし、可能であれば、それを避けたいと思います)。

助けてくれてありがとう。

4

1 に答える 1

1

ストップウォッチの値に基づいてタイマーがラベルを更新するようにしたいことを前提としています。そうですか?

少しハッキーなことを試してみてください。
次のようにストレージクラスを定義します。

Public Class StopwatchStorage
    Public Property Stopwatch as Stopwatch
    Public Property Label as Label
    Public Property Timer as Timer
End Class

フォームの上部でプライベートリストを定義します。

Private _storage as new List(Of StopwatchStorage)

forループの最後にこれを実行します

Dim storage As New StopwatchStorage()
storage.Label = participantClock
storage.Timer = participantTimer
storage.Stopwatch = participantStopwatch
_storage.Add(storage)
AddHandler participantTimer.Tick, AddressOf Timer_Tick

上記のコードを使用すると、tick関数で必要な3つのオブジェクトにアクセスできます。オブジェクトの正しい「セット」を見つけるには、_storageリストをループする必要がありますが、機能するはずです。

Private Sub Timer_Tick(sender As Object, args As EventArgs)
    For Each storage As StopwatchStorage In _storage
        If storage.Timer Is sender Then
            storage.Label.Text = storage.Stopwatch.Elapsed
            Exit Sub
        End If
    Next
End Sub

私はそのコードをコンパイルしようとしなかったので、いくつかのタイプミスがあると確信していますが、オブジェクトの名前を使用せずにオブジェクトを参照する方法がわかるはずです。

于 2012-02-03T06:54:50.407 に答える