[VB.NET] การใส่ปุ่มคำสั่งเข้าไปใน TextBox หรือที่เราเรียกว่า SearchBox (VB2010)
http://www.g2gnet.com/webboard/images/vbnet/SearchBoxRun.pngสำหรับ VB.NET รุ่น 2010 จะไม่มี Control แบบที่ช่อง TextBox จะมีปุ่มคำสั่ง (Button) อยู่ภายใน ... แต่ทว่าเราสามารถสร้าง UserControl ขึ้นมาใช้งานเองก็ได้ แต่นั่นมันดูยุ่งยากเกินไป วันนี้แอดมินจะใช้วิธีการที่เรียกว่า Inherits Function หรือการสืบพันธุ์ เอ้ย สืบทอดในรูปแบบฟังค์ชั่นแทน ...
อันดับแรกก็ต้องสร้างโปรเจคขึ้นมาใหม่ก่อน ... จากนั้นก็ใส่โค้ดตามข้างล่างนี้ในฟอร์มหลัก (Form1)
Public Class Form1
'//
End Class
Public Class TextBoxButton
Inherits TextBox
Public mButton As Button
Public Property Button As Button
Get
Return mButton
End Get
Set(value As Button)
mButton = value
End Set
End Property
Protected Overrides Sub OnCreateControl()
Me.Controls.Add(Me.mButton)
Me.mButton.Dock = DockStyle.Right
MyBase.OnCreateControl()
End Sub
Public Sub New()
MyBase.New()
mButton = New Button
'// Properties
With Me.mButton
.Width = 20
.FlatAppearance.BorderSize = 0
'// If you want to use "Text" properties, You have to change it to "System".
.FlatStyle = FlatStyle.Popup
.BackColor = Color.Transparent
.Cursor = Cursors.Hand
.Image = My.Resources.Search
'.Text = "..."
End With
'// Event Handler
AddHandler mButton.Click, AddressOf MyClick
End Sub
'// Event/Driven
Private Sub MyClick(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Ohhhh !!! You click me.")
End Sub
'// Clean up memory.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (mButton Is Nothing) Then
mButton.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
End Class
อย่าพึ่งรันครับ เดี๋ยวเราไปใส่รูปเข้ามายัง Resource ก่อน
การเพิ่มรูปภาพ เพื่อนำไปใส่ยังปุ่มคำสั่ง ... โดยเลือกเมนู Project --> ชื่อโปรเจค Properties ...
http://www.g2gnet.com/webboard/images/vbnet/SearchBoxImage.png
เลือก Add Existing File จากนั้นก็ทำการ Browse เพื่อหาไฟล์ภาพที่เราต้องการ ...
http://www.g2gnet.com/webboard/images/vbnet/SearchBoxResource.png
สำเร็จเสร็จสมบูรณ์ ...
เลือก Build ...
http://www.g2gnet.com/webboard/images/vbnet/SearchBoxBuild.png
เลือก Form1 ให้ดูที่กลุ่มเครื่องมือ ToolBox ก็จะปรากฏ Control ตัวใหม่ขึ้นมา ...
http://www.g2gnet.com/webboard/images/vbnet/SearchBoxDesign.png
ก็จัดการจับลากมาวางบนฟอร์มได้เลยทันที หรือดับเบิ้ลคลิ๊กเบาๆ 1 ทีพอครับ ...
จบแต่เพียงเท่านี้แหละครับ ... ดาวน์โหลดโค้ดฉบับเต็ม VB.NET (2010) ได้ที่นี่ ...
หน้า:
[1]