开发者

Connect label with the control it represents

I've been pondering on this problem for some time now. Is there a neat way to "connect" a Label with a control it's labeling in a functional way?

For example, you have a form to create a new user profile. If a user doesn't fill out a necessary field, the Label of that Text开发者_如何学CBox, or NumericUpDown or what not, turn red. Somehow, the Label has to know which Control it belongs to, and vice versa.

What I do right now is search for the correct label by its .Name property, which matcher (partly) with the .Name property of my text box. That ugly method looks somewhat like this (VB.NET):

Dim redLabel As Label

For Each txt As Control In Me.Controls
    If (TypeOf txt Is TextBox And txt.Text = "") Or _
       (TypeOf txt Is NumericUpDown And txt.Text = "0") Then

        'Change corresponding label color to red'
        redLabel = CType(Me.Controls.Find("Label" & _
                         txt.Name.Remove(0, "TextBox".Length), True)(0), Label)
        redLabel.ForeColor = Color.Red
        'Get name of the non-filled field'
        boxesNotFilled.Add(redLabel.Text)

    End If
Next

I could make a custom control that does the job, but I don't want to if I don't have to (the classic problem of reinventing the wheel). The question logically follows: is there a way to provide for such interaction between controls without searching for them and using not-at-all-safe control naming as convention, without writing custom controls?

Cheers! = )


I would go with a custom UserControl for something like this. It takes less time to write a simple UserControl than it does to post a question to StackOverflow. :)


How about just starting with a RequiredFieldValidator? That'll give you the ControlToValidate property at runtime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜