在文本框中显示 DateTimePicker
Posted
技术标签:
【中文标题】在文本框中显示 DateTimePicker【英文标题】:Show DateTimePicker in Textbox 【发布时间】:2016-12-05 14:46:57 【问题描述】:我设置了 DatetimePicker.Visible=False,当我点击文本框时,我希望它显示在文本框内。我的代码适用于 1 个文本框,但不适用于另一个:
Private Sub Show_DTP(Ctl As Control)
Dim x As Integer = 0
Dim y As Integer = 0
Dim Width As Integer = 0
Dim height As Integer = 0
Dim rect As Rectangle
Select Case Ctl.Name
Case "TxtTest"
rect = TxtTest.DisplayRectangle()
x = rect.X + TxtTest.Left
y = rect.Y + TxtTest.Top
Width = rect.Width + 4
height = rect.Height
With My_DTP
.SetBounds(x, y, Width, height)
.Visible = True
.Focus()
End With
Case "Txt2"
rect = Txt2.DisplayRectangle()
x = rect.X + Txt2.Left
y = rect.Y + Txt2.Top
Width = rect.Width + 4
height = rect.Height
With My_DTP
.SetBounds(x, y, Width, height)
.Visible = True
.Focus()
End With
End Select
End Sub
Private Sub Text_Click(sender As Object, e As EventArgs) Handles TxtTest.Click, Txt2.Click
Dim Txt As System.Windows.Forms.TextBox = DirectCast(sender, TextBox)
My_DTP.Visible = False
Show_DTP(Txt)
End Sub
这里有什么问题?
【问题讨论】:
你想要完成什么? case 语句后没有“Exit Select”(c# 的情况下中断) @Plutonix,我想在一些文本框中显示相同的 DTP。我将使用这个 DTP 将它的值输入到文本框中。 @KarthikGanesan,退出选择没有任何作用。这很奇怪,但如果我删除 1 个文本框并添加新的,我的代码实际上可以工作。这就像一个错误。 @KarthikGanesan :Exit Select
在那里不需要。 VB.NET 的 Case
语句不会失败。见Why should I use exit select?
【参考方案1】:
不需要 case 语句:不管实际的文本框如何,你都做同样的事情。
我在表单上放置了两个名为“TxtTest”和“Txt2”的文本框,并添加了一个名为“MyDTP”的 DateTimePicker。使用以下代码,它的行为就像您想要的那样:
Option Infer On
Option Strict On
Public Class Form1
Private Sub Show_DTP(target As TextBox)
Dim rect As Rectangle = target.DisplayRectangle()
Dim x As Integer = rect.X + target.Left
Dim y As Integer = rect.Y + target.Top
Dim width = rect.Width + 4
Dim height = rect.Height
With MyDTP
.SetBounds(x, y, Width, height)
.Visible = True
.Focus()
End With
End Sub
Private Sub Text_Click(sender As Object, e As EventArgs) Handles TxtTest.Click, Txt2.Click
Dim Txt As System.Windows.Forms.TextBox = DirectCast(sender, TextBox)
MyDTP.Visible = False
Show_DTP(Txt)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyDTP.Visible = False
End Sub
End Class
【讨论】:
以上是关于在文本框中显示 DateTimePicker的主要内容,如果未能解决你的问题,请参考以下文章