热点推荐:ASP.Net | ADO.Net | VB.Net | Web服务器 | Access | MSSQL | MySQL | Oracle | .Net控件 | Win 9x | Win 2000 | Win 2003 | DOS | Unix | 注册表 | 应用其它 | 安装调试 | 基本操作 | 使用技巧 | 系统优化 |故障处理 | 个性风格 | 病毒安全 | 专杀工具
您现在的位置: 中华IT技术网 >> 控件组件 >> .Net控件 >> 正文
全文
学习用户自定义控件
作者:佚名    文章来源:本站原创    更新时间:2007-2-1
   以下是我作的一个一个练习,来看vb.net 入门经典。
一、建立一个打开文件的用户控件
   在VS2005中,新建一个Window 控件库项目,然后创建一个用户控件。
Imports System.IO
Imports System.ComponentModel


Public Class FileButton
    Inherits System.Windows.Forms.Button
    'event...
    Public Event OpenFile(ByVal sender As Object, ByVal e As OpenFileEventArgs)
    'memebers...
    Private _buddyBoxName As String
    'BuddyBoxName Property
    Property BuddyBoxName() As String
        Get
            Return _buddyBoxName
        End Get
        Set(ByVal value As String)
            _buddyBoxName = value
        End Set
    End Property

    'GetBuddyBox-return the actual TextBox control by looking through
    'the parent's Controls property
    Public Function GetBuddyBox() As TextBox
        'serch name...
        Dim searchFor As String = BuddyBoxName.ToLower
        'look through each control...
        Dim control As Control
        For Each control In Parent.Controls
            'does the name match?
            If control.Name.ToLower = searchFor Then
                'we have a match... now,cast the control
                'to a text box and return...
                Return CType(control, TextBox)
            End If
        Next
    End Function

    Private Sub FileButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
        'try and get the buddy box...
        Dim buddyBox As TextBox = GetBuddyBox()
        If buddyBox Is Nothing Then
            MessageBox.Show("The buddy box could not be found.")
        Else
            'open the file and return the results...
            Dim stream As Stream = File.Open(buddyBox.Text, FileMode.Open)
            Dim reader As New StreamReader(stream)
            'load the entire file...
            Dim contents As String = reader.ReadToEnd
            'close the stream and the reader...
            stream.Close()
            reader.Close()
            'do something with the contents
            'raise the OpenFile event
            Dim args As New OpenFileEventArgs
            args.FileName = buddyBox.Text
            args.FileText = contents
            RaiseEvent OpenFile(Me, args)

        End If

    End Sub

End Class

二、测试
建立Window工程,加一个窗体,加一个TextBox,再引用上面生成的.dll
然后从选项卡中添加上面的控件FileButton,然后将它拖到画面上。将FileButton的属性BuddyBoxName设为TextBox.name.
加上代码:
    Private Sub FileButton1_OpenFile(ByVal sender As System.Object, ByVal e As UserControl.OpenFileEventArgs) Handles FileButton1.OpenFile
        MessageBox.Show(e.FileName & Chr(13) & e.FileText)
    End Sub

运行,设一下TextBox中的文件路径,单击FileButton1可以打开些文件了。

相关文章
最新更新
编辑推荐
热门图片
频道大全
文章阅读排行
周排行
月排行