meo vat vb.net

71
Nhấn phím Enter thì kích hoạt phím TAB Trong vb.net 2003, trên 1 form,trong khi bạn design, các điều khiển nhập liệu sẽ được quy định theo thứ tự tạo trước sau, khi bạn thực thi, mặc nhiên khi bạn nhấn phím TAB, cursor sẽ tự động nhảy đến đối tượng được tạo tiếp theo. Còn bạn nhấn enter thì không được, nếu muốn điều đó, bạn có thể làm như sau: khai báo thuộc tính KeyPreview của form = TRUE. Sau đó trong sự kiện KeyDown của form: 'giả sử tên của form đó là frmViDu Private Sub frmViDu_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp If e.KeyCode = Keys.Enter Then SendKeys.Send("{TAB}") End If End Sub Tạo hộp About động trong VB.net Bạn muốn thu lấy thông tin phiên bản lúc thực thi với mục đích hiển thị trong hộp About. Thu lấy một tham chiếu đến assembly hiện hành bằng Assembly. GetExecutingAssembly, và thu lấy AssemblyName của nó (có kèm thông tin phiên bản trong đó). Đối với một ứng dụng, thật quan trọng khi nói đúng phiên bản của nó (và đôi lúc có thêm các thông tin như tên file và bản địa) mà không cần phải viết mã cứng cho dữ liệu này. Cơ chế phản chiếu cung cấp một giải pháp lý tưởng vì nó cho phép thu lấy các chi tiết này một cách trực tiếp từ siêu dữ liệu của assembly.

Upload: api-3736517

Post on 14-Nov-2014

37 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Meo vat VB.Net

Nhấn phím Enter thì kích hoạt phím TABTrong vb.net 2003, trên 1 form,trong khi bạn design, các điều khiển nhập liệu sẽ được quy định theo thứ tự tạo trước sau, khi bạn thực thi, mặc nhiên khi bạn nhấn phím TAB, cursor sẽ tự động nhảy đến đối tượng được tạo tiếp theo. Còn bạn nhấn enter thì không được, nếu muốn điều đó, bạn có thể làm như sau:khai báo thuộc tính KeyPreview của form = TRUE. Sau đó trong sự kiện KeyDown của form:'giả sử tên của form đó là frmViDu

Private Sub frmViDu_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUpIf e.KeyCode = Keys.Enter ThenSendKeys.Send("{TAB}")End IfEnd Sub

Tạo hộp About động trong VB.netBạn muốn thu lấy thông tin phiên bản lúc thực thi với mục đích hiển thị trong hộp About.Thu lấy một tham chiếu đến assembly hiện hành bằng Assembly. GetExecutingAssembly, và thu lấy AssemblyName của nó (có kèm thông tin phiên bản trong đó).Đối với một ứng dụng, thật quan trọng khi nói đúng phiên bản của nó (và đôi lúc có thêm các thông tin như tên file và bản địa) mà không cần phải viết mã cứng cho dữ liệu này. Cơ chế phản chiếu cung cấp một giải pháp lý tưởng vì nó cho phép thu lấy các chi tiết này một cách trực tiếp từ siêu dữ liệu của assembly.Đoạn mã dưới đây hiển thị vài mẩu thông tin về assembly hiện hành bằng cơ chế phản chiếu. Nó cũng trình bày cách thu lấy những thông tin đó một cách gián tiếp từ lớp System.Windows.Forms.Application (bất chấp kiểu ứng dụng là gì).Public Module TestReflection    Public Sub Main()        Dim ExecutingApp As System.Reflection.Assembly        ExecutingApp = System.Reflection.Assembly.GetExecutingAssembly()        Dim Name As System.Reflection.AssemblyName        Name = ExecutingApp.GetName()        ' Hiển thị thông tin siêu dữ liệu.

Page 2: Meo vat VB.Net

        Console.WriteLine("Application: " & Name.Name)        Console.WriteLine("Version: " & Name.Version.ToString())        Console.WriteLine("Code Base: " & Name.CodeBase)        Console.WriteLine("Culture: " & Name.CultureInfo.DisplayName)        Console.WriteLine("Culture Code: " & Name.CultureInfo.ToString())        ' (Nếu assembly đã được ký, bạn có thể sử dụng Name.KeyPair        '  để thu lấy khóa công khai.)        ' Một số thông tin được lấy từ lớp Application.        ' Thông tin phiên bản là giống hệt.        Console.WriteLine("Assembly File: " & _          System.Windows.Forms.Application.ExecutablePath)        Console.WriteLine("Version: " & _          System.Windows.Forms.Application.ProductVersion)        ' Thông tin Company và Product được thiết lập thông qua        ' đặc tính AssemblyCompany và AssemblyProduct (thường        ' nằm trong file AssemblyInfo.vb).        Console.WriteLine("Company: " & _          System.Windows.Forms.Application.CompanyName)        Console.WriteLine("Product: " & _          System.Windows.Forms.Application.ProductName)        ' Thông tin bản địa là bản địa hiện hành        ' (trong trường hợp này là en-US), trong khi        ' cơ chế phản chiếu thu lấy bản địa được chỉ định        ' trong assembly (trong trường hợp này là không có).        Console.WriteLine("Culture: " & _          System.Windows.Forms.Application.CurrentCulture.ToString())        Console.WriteLine("Culture Code: " & _          System.Windows.Forms.Application.CurrentCulture.DisplayName)        Console.ReadLine()    End SubEnd ModuleChú ý rằng GetExecutingAssembly luôn trả về một tham chiếu đến assembly mà mã lệnh đang thực thi ở đó. Nói cách khác, nếu bạn chạy một ứng dụng Windows (assembly A) có sử dụng một thành phần độc lập (assembly B), và thành phần đó cho gọi GetExecutingAssembly, nó sẽ nhận được một tham chiếu đến assembly B. Bạn cũng có thể sử dụng GetCallingAssembly (thu lấy assembly mà lệnh gọi được định vị ở đó) hoặc GetEntryAssembly (trả về assembly có thể thực thi đối với miền ứng dụng hiện hành). Assembly là một từ khóa dành riêng trong Microsoft Visual Basic .NET.

Page 3: Meo vat VB.Net

Do đó, nếu muốn tham chiếu kiểu System.Reflection.Assembly, bạn phải sử dụng tham chiếu dạng đầy đủ hoặc bạn phải đặt từ Assembly trong dấu ngoặc vuông.' Lệnh này làm việc.Dim Asm As System.Reflection.Assembly

' Lệnh này cũng làm việc,' giả sử bạn đã nhập không gian tên System.Reflection.Dim Asm As [Assembly]

' Lệnh này sinh ra lỗi biên dịch,' vì Assembly là từ khóa dành riêng.Dim Asm As Assembly

Tạo form với hiệu ứng DropShadowrất đơn giản,bạn chỉ cần khai báo tham số CS_DROPSHADOW và với nó bạn có thể làm cho bất cứ Window nào cũng sẽ có một cái bóng như dưới đây bằng trao cho lớp của nó tham số trên:

[vb]Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams Get Dim parameters As CreateParams = MyBase.CreateParams parameters.ClassStyle = parameters.ClassStyle Or CS_DROPSHADOW Return parameters End Get End Property[/vb]

Lấy khoảng thời gian giữa thời điểm (bắt đầu làm gì đó) và thời điểm kết thúc :Private Function GetDuration(ByVal timeStart As DateTime) As String

        Dim timeElapsed As New TimeSpan(0)        Dim timeEnd As DateTime        Dim timeDifference As New TimeSpan

        timeEnd = DateTime.Now()        timeDifference = timeEnd.Subtract(timeStart)        timeElapsed = timeElapsed.Add(timeDifference)        Return timeElapsed.ToString()

Page 4: Meo vat VB.Net

End Function

'Lấy time thực hiện một số câu lệnh

Implementation

Dim timeStart As DateTime

timeStart = DateTime.Now()

' các câu lệnh làm chuyện gì đó

Me.lblDuration.Text = GetDuration(timeStart)

và lấy kiểu ngày không có gắn giờDim _date As Date = DateTime.Now.Date

SubClass trong .NET Trính: “…Windows gửi thông điệp là một hằng số tới các form và các control của VB để báo cho chúng biết vị trí chuột ở đâu, khi nào thì cần vẽ lại, phím nào đang được nhấn và nhiều thông điệp khác. Kỹ thuật subclassing là để xử lý chặn những thông điệp này trước khi chúng đến được các form và control. Bằng cách chặn các thông điệp này và xử lý ''vài thứ'' trước khi chúng đến đích, chúng ta có thể có các tính năng riêng (như tự vẽ lại các control theo ý riêng).Subclassing là một kỹ thuật tinh vi, chỉ cần một lỗi nhỏ (ví dụ như : do bạn giải phóng tài nguyên không tốt dẫn đến việc thất thoát tài nguyên của hệ thống) là có thể dẫn đến việc hệ thống của bạn bị thiếu tài nguyên làm cho hệ thống hoạt động không còn tốt nữa (chậm đi), nặng hơn là VB bị shut down, thậm chí treo máy. Tuy nhiên nói điều này là để bạn ý thức được vấn đề chứ bạn cũng không nên quá lo ngại về nó. Và thêm 1 chú ý là bạn cũng không nên bấm nút stop của VB khi chương trình đang chạy mà bạn nên đóng form 1 cách thông thường (bấm nút close) để thực hiện tốt việc giải phóng tài nguyên…” Trong VB6 bạn có thể dùng Kỹ thuật này bằng cách tạo ra một Lớp và dùng các hàm API như : SetWindowLong,CallWindowProc,hay Sendmessage và một số tin nhắn. Còn trong .NET bạn có thể bắt tin nhắn và xứ lí chúng bằng cách dùng phương thức WndProc trong Form như sau: [vb]Protected Overrides Sub WndProc(ByRef m As

Page 5: Meo vat VB.Net

System.Windows.Forms.Message) Select Case m.Msg Case WM_MOUSEMOVE 'xử lí tin nhắn ở đây End Select End Sub[/vb] Nhưng cách dùng trên có một vài nhược điểm như một số Control không có phương thức này và giống như lí do mà trong VB6 bạn phải tạo một lớp riêng để SubClass.Vì vậy việc SubClass trong .NET sẽ dễ dàng hơn khi dùng Lớp NativeWindow.Bạn có thể tạo bằng cách tạo một lớp mới và thừa hưởng lại từ Lớp NativeWindow.

[vb]Imports System.Runtime.InteropServices Imports System.Drawing Imports System.Drawing.Drawing2D

Public Class Class1 : Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Select Case m.Msg Case WM_NCACTIVATE 'Sứ lí tin nhắn ở đây End Select MyBase.WndProc(m) End Sub End Class[/vb] Cách dùng lớp này như sau: Trong NativeWindow có 3 phương thức mà bạn dùng để bắt đầu với kỹ thuật SubClass trong .NET 1. AssignHandle( handle as IntPtr): Gán một đối tượng vào handle của cửa sổ và bắt đầu Subclass. 2. ReleaseHandle( handle as IntPtr): Huỷ bỏ Subclass và đưa giá trị của handle về già trị 0. [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load s.AssignHandle(Me.Handle)

Page 6: Meo vat VB.Net

End Sub

Private Sub Form1_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Closed s.ReleaseHandle() End Sub[/vb] Ok!

Cách truy vần dữ liệu trực tiếp trong datasetVề lớp không kết nối Dataset. Mình muốn hỏi các bạn là có cách nào để truy vấn trực tiếp thông tin trong dataset không. Ví dụ mình có một bảng tên là Mathang với 3 cột : MaHang,TenHang,GiaBan. Trong chương trình của mình khi user thay đổi mã hàng thì mình sẽ tìm các thông tin còn lại bằng câu lệnh SQL sau: Select * from MatHang Where Mahang like "mahang*" thì tất nhiên nó sẽ cho ra kết quả. Nhưng nếu vậy thì mỗi lần đổi mã hàng là mỗi lần connect đến server, sau đó select dữ liệu rồi trả về biến dataset, rồi lại đưa vào datagrid. Như vậy sẽ rất lâu và không tối ưu. Ý tưởng của mình là trước khi vào Form thì mình sẽ Select hết thông tin trong bảng Mathang lưu vào biến toàn cục dataset. Sau đó chương trình sẽ chỉ select trên dataset này mà thôi và không cần kết nối lại server nữa như vậy sẽ rất là nhanh, các bạn có đồn ý với mình không? Nhưng vấn đề là làm sao có thể làm cho dataset hiểu được câu lệnh SQL mà trả về thông tin minh cần và đưa vào datagrid sau đó show cho user xem??

Về vấn đề này, bạn có thể dùng một mảng datarow để lọc những dòng thỏa điều kiện, bạn làm như vầy: Dim dr as datarow() dr=ds.Tables("Mathang").Select("Mahang like '" & mahang & "*'")

Cách cài đặt 1 ứng dụng VB2005.NET trên mạng LAN như thế nàoTôi có 1 ứng dụng viết bằng VB.NET. Khi chạy ứng dụng trên máy cài đặt chương trình thì nó hoạt động bình thường. Tôi có tạo một shortcut đến chương trình từ một máy tính khác trong mạng LAN và chạy chương trình từ shortcut này thì xuất hiện thông báo lỗi như sau:

Application attempted to perform an operation not allowed by theSecurity policy. To grant this application the required permission, contact

Page 7: Meo vat VB.Net

Your system administrator, or use the Microsoft .NET FrameworkConfiguration tool.

If you click Continue, the application will ignore this error and attempt toContinue. If you click Quit, the application will close immediately.

Request for the permission of type‘System.Data.OleDb.OleDbPermission, System.Data, Version=2.0.0.0,Culture=neutral, PulicKeyToken=b77a5c561934e089’ failed.

Tôi biết rằng lỗi trên là do chương trình có sử dụng cơ sở dữ liệu Access và không biết cách khác phục như thế nào. Nhờ các chuyên gia về VB.NET hướng dẫn tôi cài đặt chương trình như thế nào để mọi máy trong mạng LAN đều có thể sử dụng chung chương trình được cài trên 1 máy.Cấu hình mặc định của net framwork không cho phép chạy các net APP trên network vì nó được cho là untrust, muốn các net APP triển khai được trên các untrust location như maped network cần làm theo bước sau :Vào settings - ... Control Panel... Administrative tools... Microsoft .NET Framework Configuration... nhắp phải vào Runtime Security Policy... chọn Adjust Security... rùi nhấn next... chỉnh Local Intranet sang "Full Trust"... rùi NEXT... Vậy là ok........

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib "kernel32.dll" () As Long' Exposed EnumerationPublic Enum mceItemStates    mceDisabled = 1    mceGrayed = 2End Enum

' Property variablesPrivate psCaption As String ' Caption of menu item (with the arrow >) if this is submenuPrivate piHwnd As Long ' Handle to Menu

' Supporting API codePrivate Const GW_CHILD = 5Private Const GW_HWNDNEXT = 2Private Const GW_HWNDFIRST = 0Private Const MF_BYCOMMAND = &H0&Private Const MF_BYPOSITION = &H400Private Const MF_CHECKED = &H8&Private Const MF_DISABLED = &H2&Private Const MF_GRAYED = &H1&Private Const MF_MENUBARBREAK = &H20&Private Const MF_MENUBREAK = &H40&

Page 8: Meo vat VB.Net

Private Const MF_POPUP = &H10&Private Const MF_SEPARATOR = &H800&Private Const MF_STRING = &H0&Private Const MIIM_ID = &H2Private Const MIIM_SUBMENU = &H4Private Const MIIM_TYPE = &H10Private Const TPM_LEFTALIGN = &H0&Private Const TPM_RETURNCMD = &H100&Private Const TPM_RIGHTBUTTON = &H2

Private Type POINT    X As Long    Y As LongEnd TypePrivate Type RECT    Left As Long    Top As Long    Right As Long    Bottom As LongEnd TypePrivate Type MENUITEMINFO    cbSize As Long    fMask As Long    fType As Long    fState As Long    wID As Long    hSubMenu As Long    hbmpChecked As Long    hbmpUnchecked As Long    dwItemData As Long    dwTypeData As String    cch As LongEnd TypePrivate Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, lpNewItem As String) As LongPrivate Declare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As LongPrivate Declare Function DeleteMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal uFlags As Long) As LongPrivate Declare Function CreatePopupMenu Lib "user32" () As LongPrivate Declare Function EnableMenuItem Lib "user32" (ByVal hMenu As Long, ByVal wIDEnableItem As Long, ByVal wEnable As Long) As LongPrivate Declare Function GetCursorPos Lib "user32" (lpPoint As POINT) As LongPrivate Declare Function GetDesktopWindow Lib "user32" () As LongPrivate Declare Function GetWindow Lib "user32" (ByVal Hwnd As Long, ByVal wCmd As Long) As LongPrivate Declare Function GetWindowThreadProcessId Lib "user32" (ByVal Hwnd As Long, lpdwProcessId As Long) As LongPrivate Declare Function GetCurrentProcessId Lib "kernel32" () As LongPrivate Declare Function GetWindowRect Lib "user32" (ByVal Hwnd As Long, lpRect As RECT) As LongPrivate Declare Function GetMenuItemInfo Lib "user32" Alias "GetMenuItemInfoA" (ByVal hMenu As Long, ByVal un As Long, ByVal b As Boolean, lpMenuItemInfo As MENUITEMINFO) As BooleanPrivate Declare Function GetFocus Lib "user32" () As LongPrivate Declare Function GetForegroundWindow Lib "user32" () As LongPrivate Declare Function SetMenuDefaultItem Lib "user32" (ByVal hMenu As Long, ByVal uItem As Long, ByVal fByPos As Long) As LongPrivate Declare Function TrackPopupMenuEx Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal X As Long, ByVal Y As Long, ByVal Hwnd As Long, ByVal lptpm As Any) As LongPrivate Declare Function SetMenuItemBitmaps Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long, ByVal hBitmapUnchecked As Long, ByVal

Page 9: Meo vat VB.Net

hBitmapChecked As Long) As LongPrivate Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As LongPublic Property Let Caption(ByVal sCaption As String)

    psCaption = sCaption    End Property

Public Property Get Caption() As String

    Caption = psCaption    End Property

Public Sub Remove(ByVal iMenuPosition As Long)        DeleteMenu piHwnd, iMenuPosition, MF_BYPOSITION    End Sub

Private Sub Class_Initialize()    piHwnd = CreatePopupMenu()End Sub

Private Sub Class_Terminate()    DestroyMenu piHwndEnd Sub

Public Property Get Hwnd() As Long        Hwnd = piHwnd

End Property

Public Sub Add(ByVal iMenuID As Long, vMenuItem As Variant, Optional bDefault As Boolean = False, Optional bChecked As Boolean = False, Optional eItemState As mceItemStates, Optional ByVal imgUnchecked As Long = 0, Optional ByVal imgChecked As Long = 0)        ' Check to see if it's a menu item (a string) or a submenu (a class).    If TypeName(vMenuItem) = "String" Then                If vMenuItem = "-" Then ' Make a seperator            AppendMenu piHwnd, MF_STRING Or MF_SEPARATOR, iMenuID, ByVal vbNullString        Else            AppendMenu piHwnd, MF_STRING Or -bChecked * MF_CHECKED, iMenuID, ByVal vMenuItem        End If            ' Menu Icons        If imgChecked = 0 Then imgChecked = imgChecked ' Need a value for both        SetMenuItemBitmaps piHwnd, iMenuID, MF_BYCOMMAND, imgUnchecked, imgChecked                ' Default item        If bDefault Then SetMenuDefaultItem piHwnd, iMenuID, 0                ' Disabled (Regular color text)

Page 10: Meo vat VB.Net

        If eItemState = mceDisabled Then EnableMenuItem piHwnd, iMenuID, MF_BYCOMMAND Or MF_DISABLED        ' Disabled (disabled color text)        If eItemState = mceGrayed Then EnableMenuItem piHwnd, iMenuID, MF_BYCOMMAND Or MF_GRAYED        ' Add a submenu    ElseIf TypeOf vMenuItem Is mcPopupMenu Then        Dim oSubmenu As mcPopupMenu: Set oSubmenu = vMenuItem        AppendMenu piHwnd, MF_STRING Or MF_POPUP, oSubmenu.Hwnd, ByVal oSubmenu.Caption        Set oSubmenu = Nothing    End If

End Sub

Public Function Show(Optional ByVal iFormHwnd As Long = -1, Optional ByVal X As Long = -1, Optional ByVal Y As Long = -1, Optional ByVal iControlHwnd As Long = -1) As LongDim iHwnd As Long, iX As Long, iY As Long        ' If no form is passed, use the current window    If iFormHwnd = -1 Or iFormHwnd = 0 Then                Dim iDesktopHwnd As Long, iChildHwnd As Long, iCurrentID As Long, iChildID As Long                iDesktopHwnd = GetDesktopWindow()        iChildHwnd = GetWindow(iDesktopHwnd, GW_CHILD)        iCurrentID = GetCurrentProcessId()        Do While iChildHwnd            GetWindowThreadProcessId iChildHwnd, iChildID            If iChildID = iCurrentID Then Exit Do ' Snagged            iChildHwnd = GetWindow(iChildHwnd, GW_HWNDNEXT)        Loop                If iChildHwnd = 0 Then ' Can't resolve a form handle. Bail out.            Show = -1            Exit Function        End If        iHwnd = iChildHwnd    Else        iHwnd = iFormHwnd    End If        ' If passed a control handle, left-bottom orient to the control.    If iControlHwnd <> -1 Then        Dim rt As RECT        GetWindowRect iControlHwnd, rt        iX = rt.Left        iY = rt.Bottom    Else        Dim pt As POINT        GetCursorPos pt        If X = -1 Then iX = pt.X Else: iX = X        If Y = -1 Then iY = pt.Y Else: iY = Y    End If    Show = TrackPopupMenuEx(piHwnd, TPM_RETURNCMD Or TPM_RIGHTBUTTON, iX, iY, iHwnd, ByVal 0&)    End Function

Page 11: Meo vat VB.Net

Dynamic Menu Form coding

Option Explicit

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)

    lblLabel.BackColor = vbButtonFace    lblLabel.ForeColor = vbWindowText    End Sub

Private Sub lblLabel_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)

    lblLabel.BackColor = vbHighlight    lblLabel.ForeColor = vbHighlightText

End Sub

Private Sub lblLabel_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)

    Dim oMenu As mcPopupMenu: Set oMenu = New mcPopupMenu    Dim oSubmenu1 As mcPopupMenu: Set oSubmenu1 = New mcPopupMenu    Dim oSubmenu2 As mcPopupMenu: Set oSubmenu2 = New mcPopupMenu    Dim oSubmenu3 As mcPopupMenu: Set oSubmenu3 = New mcPopupMenu    Dim x1 As Single, y1 As Single, Ret As Long        ' Labels don't have a handle, set x,y manually    x1 = (Me.Left + 45 + lblLabel.Left) / 15 ' 15 twips per pixel    y1 = (Me.Top + 525 + lblLabel.Height) / 15        ' Add a few of the main menu items    oMenu.Add 1, "Item 1"    oMenu.Add 2, "Item 2", True, , , imglstImages.ListImages(1).Picture    oMenu.Add 3, "Item 3", , , mceGrayed        oMenu.Add 4, "-" ' Seperator        ' Build our submenus when needed    oSubmenu1.Caption = "Submenu 1"    oSubmenu1.Add 20, "Submenu 1 Item 1", , , mceGrayed, imglstImages.ListImages(2).Picture    oSubmenu1.Add 21, "Submenu 1 Item 2", , , , imglstImages.ListImages(3).Picture    oSubmenu1.Add 22, "Submenu 1 Item 3", , , , imglstImages.ListImages(4).Picture        ' Submenu of the first submenu    oSubmenu2.Caption = "Submenu 2"    oSubmenu2.Add 30, "Submenu 2 Item 1"    oSubmenu2.Add 31, "Submenu 2 Item 2"    oSubmenu2.Add 32, "Submenu 2 Item 3"        ' Add second submenu to first    oSubmenu1.Add 33, oSubmenu2        ' Add first submenu to main.    oMenu.Add 5, oSubmenu1        oMenu.Add 6, "-" ' Another seperator   

Page 12: Meo vat VB.Net

    ' Build third submenu    oSubmenu3.Caption = "Submenu 3"    oSubmenu3.Add 40, "Submenu 2 Item 1", , , , imglstImages.ListImages(2).Picture    oSubmenu3.Add 41, "Submenu 3 Item 2", , , , imglstImages.ListImages(3).Picture    oSubmenu3.Add 42, "Submenu 3 Item 3", , , , imglstImages.ListImages(4).Picture        oMenu.Add 7, oSubmenu3        oMenu.Add 8, "-" ' Yet another        ' The remaining items in the main menu    oMenu.Add 9, "Item 4", , True    oMenu.Add 10, "Item 5", , , , imglstImages.ListImages(4).Picture    oMenu.Add 11, "Item 6", , True, mceGrayed        ' Show popup    Ret = oMenu.Show(Me.Hwnd, x1, y1)        ' Release objects    Set oSubmenu1 = Nothing: Set oSubmenu2 = Nothing: Set oSubmenu3 = Nothing: Set oMenu = Nothing            MsgBox "You chose menu ID " & Ret        Select Case Ret            ' Lights, camera, action!        End Select

End Sub

.NET System Information Class Demo

This class encapsulates the .NET system information class, which allows you to easily get information about the system your process is running on. It only uses a subset of the SystemInformation class; you can look in help or use intellisense (SystemInformation.) to get an idea of what else this it can do. To quickly see what information you can get from the class presented here, run the following in the IDE:

Dim objSysInfo As New clsSystemInfo() With objSysInfo Debug.WriteLine("Boot Mode: " & .BootMode) Debug.WriteLine("Computer Name: " & .ComputerName) Debug.WriteLine("Double Byte Character Set Enabled: " _ & .DBCSEnabled) Debug.WriteLine("Network Connection Present: " & .isConnectedToNetwork) Debug.WriteLine("Menu Font Name: " & .MenuFontName) Debug.WriteLine("Menu Font Name: " & .MenuFontSize) Debug.WriteLine("Menu Height: " & .MenuHeight) Debug.WriteLine("Hebrew and Arabic supported: " & .MidEastEnabled) Debug.WriteLine("# of attached monitors: " & .MonitorCount) Debug.WriteLine("Is mouse present: " & .MousePresent) Debug.WriteLine("Is mouse wheel present: " & .MouseWheelPresent) Debug.WriteLine("# of mouse buttons: " & .MouseButtons) Debug.WriteLine("Is Pen Windows Supported: " & .PenWindows)

Page 13: Meo vat VB.Net

Debug.WriteLine("Primary Monitor Size: " & .PrimaryMonitorSize) Debug.WriteLine("Is OS Security Present:" & .Secure) Debug.WriteLine("Domain Name: " & .UserDomainName) Debug.WriteLine("User Name: " & .UserName) Debug.WriteLine("Current process running in user interactive mode:" & .UserInteractive) Debug.WriteLine("Working Area: " & .WorkingArea)

CodePublic Class clsSystemInfo Public Function BootMode() As String ' Normal: The computer started in the standard mode 'FailSafe: The computer started with only the basic 'files and drivers to run locally 'FailSafeWithNetwork: The computer started with the 'basic files, drivers, etc to run on network

Return SystemInformation.BootMode.ToString

End Function Public Function ComputerName() As String 'the computername Return SystemInformation.ComputerName

End Function Public Function DBCSEnabled() As Boolean 'returns true if system is capable of 'handling double-byte character set (DBCS) characters. Return SystemInformation.DbcsEnabled

End Function Public Function MenuFontName() As String 'operating system font name for menus Return SystemInformation.MenuFont.FontFamily.Name

End Function Public Function MenuFontSize() As Integer 'operating system font name for menus Return SystemInformation.MenuFont.Size

End Function Public Function MenuHeight() As Integer

Page 14: Meo vat VB.Net

'height of one menu line in pixel Return SystemInformation.MenuHeight

End Function

Public Function MidEastEnabled() As Boolean 'true if system supports Hebrew and Arabic languages. Return SystemInformation.MidEastEnabled End Function Public Function MonitorCount() As Integer 'How many monitors Return SystemInformation.MonitorCount End Function

Public Function MouseButtons() As Integer 'How many mouse buttons Return SystemInformation.MouseButtons End Function

Public Function MousePresent() As Boolean 'is mouse present Return SystemInformation.MousePresent End Function Public Function MouseWheelPresent() As Boolean 'is mouse with mouse wheel present Return SystemInformation.MouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean 'connection to network present? Return SystemInformation.Network End Function Public Function PenWindows() As Boolean 'Are Microsoft Windows for Pen Computing extensions installed Return SystemInformation.PenWindows

End Function Public Function PrimaryMonitorSize() As String 'Size of primary monitor Return SystemInformation.PrimaryMonitorSize.ToString

Page 15: Meo vat VB.Net

End Function Public Function Secure() As Boolean 'is security present on operating system Return SystemInformation.Secure

End Function Public Function UserDomainName() As String 'the domain name for the current user Return SystemInformation.UserDomainName End Function Public Function UserInteractive() As Boolean 'is current process running in user-interactive mode. Return SystemInformation.UserInteractive End Function Public Function UserName() As String 'user name Return SystemInformation.UserName End Function Public Function WorkingArea() As String Return SystemInformation.WorkingArea.ToString

End FunctionEnd Class

SQL Data Provider VB.NET Class - The Class

The Class

This class is for simplifying and accelerating working with SQL, using this class is very simple; there is a sample below for this class, which I hope is useful. You can report bugs, opinions and suggestions to me.

Imports SystemImports System.IOImports System.TextImports System.DataImports System.Data.SqlClient

Namespace SqlDataProvider

''' <summary> ''' This class provides a fast and universal method for accessing SQL Server database.This class cannot be inherited. ''' </summary> Public NotInheritable Class SqlDatabase

#Region " Local Property Declarations "

Dim _connectionString As String

Page 16: Meo vat VB.Net

#End Region

#Region " Constructor "

''' <summary> ''' Initializes a new instance of the ADO.SqlDatabase class. ''' </summary> ''' <param name="connectionString">The connection used to open the SQL Server database.</param> Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

#End Region

#Region " Public Properties "

''' <summary> ''' Gets or sets the string used to open a SQL Server database. ''' </summary> ''' <returns>The connection string that includes the source database name, and other parameters needed to establish the initial connection.</returns> Public Property ConnectionString() As String Get Return _connectionString End Get Set(ByVal value As String) _connectionString = value End Set End Property

#End Region

#Region " Private Methods "

Private Sub AssignParameters(ByVal cmd As SqlCommand, ByVal cmdParameters() As SqlParameter) If (cmdParameters Is Nothing) Then Exit Sub For Each p As SqlParameter In cmdParameters cmd.Parameters.Add(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand, ByVal parameterValues() As Object) If Not (cmd.Parameters.Count - 1 = parameterValues.Length) Then Throw New ApplicationException("Stored procedure's parameters and parameter values does not match.") Dim i As Integer For Each param As SqlParameter In cmd.Parameters If Not (param.Direction = ParameterDirection.Output) AndAlso Not (param.Direction = ParameterDirection.ReturnValue) Then param.Value = parameterValues(i) i += 1 End If Next End Sub

#End Region

#Region " ExecuteNonQuery "

''' <summary> ''' Executes a Transact-SQL statement against the connection and returns the number of rows affected. ''' </summary> ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param> ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param> ''' <param name="parameters">The parameters of the Transact-SQL statement or

Page 17: Meo vat VB.Net

stored procedure.</param> ''' <returns>The number of rows affected.</returns> Public Function ExecuteNonQuery(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Integer Dim connection As SqlConnection = Nothing Dim transaction As SqlTransaction = Nothing Dim command As SqlCommand = Nothing Dim res As Integer = -1 Try connection = New SqlConnection(_connectionString) command = New SqlCommand(cmd, connection) command.CommandType = cmdType Me.AssignParameters(command, parameters) connection.Open() transaction = connection.BeginTransaction() command.Transaction = transaction res = command.ExecuteNonQuery() transaction.Commit() Catch ex As Exception If Not (transaction Is Nothing) Then transaction.Rollback() End If Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close() If Not (command Is Nothing) Then command.Dispose() If Not (transaction Is Nothing) Then transaction.Dispose() End Try Return res End Function

''' <summary> ''' Executes a Transact-SQL statement against the connection and returns the number of rows affected. ''' </summary> ''' <param name="spname">The stored procedure to execute at the data source.</param> ''' <param name="returnValue">The returned value from stored procedure.</param> ''' <param name="parameterValues">The parameter values of the stored procedure.</param> ''' <returns>The number of rows affected.</returns> Public Function ExecuteNonQuery(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As Integer Dim connection As SqlConnection = Nothing Dim transaction As SqlTransaction = Nothing Dim command As SqlCommand = Nothing Dim res As Integer = -1 Try connection = New SqlConnection(_connectionString) command = New SqlCommand(spname, connection) command.CommandType = CommandType.StoredProcedure connection.Open() SqlCommandBuilder.DeriveParameters(command) Me.AssignParameters(command, parameterValues) transaction = connection.BeginTransaction() command.Transaction = transaction res = command.ExecuteNonQuery() returnValue = command.Parameters(0).Value transaction.Commit() Catch ex As Exception If Not (transaction Is Nothing) Then transaction.Rollback() End If Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close() If Not (command Is Nothing) Then command.Dispose() If Not (transaction Is Nothing) Then transaction.Dispose() End Try

Page 18: Meo vat VB.Net

Return res End Function

#End Region

#Region " ExecuteScalar "

''' <summary> ''' Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. ''' </summary> ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param> ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param> ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param> ''' <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> Public Function ExecuteScalar(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Object Dim connection As SqlConnection = Nothing Dim transaction As SqlTransaction = Nothing Dim command As SqlCommand = Nothing Dim res As Object = Nothing Try connection = New SqlConnection(_connectionString) command = New SqlCommand(cmd, connection) command.CommandType = cmdType Me.AssignParameters(command, parameters) connection.Open() transaction = connection.BeginTransaction() command.Transaction = transaction res = command.ExecuteScalar() transaction.Commit() Catch ex As Exception If Not (transaction Is Nothing) Then transaction.Rollback() End If Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close() If Not (command Is Nothing) Then command.Dispose() If Not (transaction Is Nothing) Then transaction.Dispose() End Try Return res End Function

''' <summary> ''' Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. ''' </summary> ''' <param name="spname">The stored procedure to execute at the data source.</param> ''' <param name="returnValue">The returned value from stored procedure.</param> ''' <param name="parameterValues">The parameter values of the stored procedure.</param> ''' <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns> Public Function ExecuteScalar(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As Object Dim connection As SqlConnection = Nothing Dim transaction As SqlTransaction = Nothing Dim command As SqlCommand = Nothing Dim res As Object = Nothing Try connection = New SqlConnection(_connectionString) command = New SqlCommand(spname, connection) command.CommandType = CommandType.StoredProcedure connection.Open()

Page 19: Meo vat VB.Net

SqlCommandBuilder.DeriveParameters(command) Me.AssignParameters(command, parameterValues) transaction = connection.BeginTransaction() command.Transaction = transaction res = command.ExecuteScalar() returnValue = command.Parameters(0).Value transaction.Commit() Catch ex As Exception If Not (transaction Is Nothing) Then transaction.Rollback() End If Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close() If Not (command Is Nothing) Then command.Dispose() If Not (transaction Is Nothing) Then transaction.Dispose() End Try Return res End Function

#End Region

#Region " ExecuteReader "

''' <summary> ''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection, and builds a System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values. ''' </summary> ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param> ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param> ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param> ''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns> Public Function ExecuteReader(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As IDataReader Dim connection As SqlConnection = Nothing Dim command As SqlCommand = Nothing Dim res As SqlDataReader = Nothing Try connection = New SqlConnection(_connectionString) command = New SqlCommand(cmd, connection) command.CommandType = cmdType Me.AssignParameters(command, parameters) connection.Open() res = command.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception Throw New SqlDatabaseException(ex.Message, ex.InnerException) End Try Return CType(res, IDataReader) End Function

''' <summary> ''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection, and builds a System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values. ''' </summary> ''' <param name="spname">The stored procedure to execute at the data source.</param> ''' <param name="returnValue">The returned value from stored procedure.</param> ''' <param name="parameterValues">The parameter values of the stored procedure.</param> ''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns> Public Function ExecuteReader(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As IDataReader Dim connection As SqlConnection = Nothing Dim command As SqlCommand = Nothing Dim res As SqlDataReader = Nothing

Page 20: Meo vat VB.Net

Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname, connection) command.CommandType = CommandType.StoredProcedure connection.Open() SqlCommandBuilder.DeriveParameters(command) Me.AssignParameters(command, parameterValues) res = command.ExecuteReader(CommandBehavior.CloseConnection) returnValue = command.Parameters(0).Value Catch ex As Exception Throw New SqlDatabaseException(ex.Message, ex.InnerException) End Try Return CType(res, IDataReader) End Function

#End Region

#Region " FillDataset "

''' <summary> ''' Adds or refreshes rows in the System.Data.DataSet to match those in the data source using the System.Data.DataSet name, and creates a System.Data.DataTable named "Table." ''' </summary> ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param> ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param> ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param> ''' <returns>A System.Data.Dataset object.</returns> Public Function FillDataset(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As DataSet Dim connection As SqlConnection = Nothing Dim command As SqlCommand = Nothing Dim sqlda As SqlDataAdapter = Nothing Dim res As New DataSet Try connection = New SqlConnection(_connectionString) command = New SqlCommand(cmd, connection) command.CommandType = cmdType AssignParameters(command, parameters) sqlda = New SqlDataAdapter(command) sqlda.Fill(res) Catch ex As Exception Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) Then connection.Dispose() If Not (command Is Nothing) Then command.Dispose() If Not (sqlda Is Nothing) Then sqlda.Dispose() End Try Return res End Function

#End Region

#Region " ExecuteDataset "

''' <summary> ''' Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the System.Data.DataSet with the specified System.Data.DataTable name. ''' </summary> ''' <param name="insertCmd">A command used to insert new records into the data source.</param> ''' <param name="updateCmd">A command used to update records in the data source.</param> ''' <param name="deleteCmd">A command for deleting records from the data set.</param> ''' <param name="ds">The System.Data.DataSet to use to update the data source. </param>

Page 21: Meo vat VB.Net

''' <param name="srcTable">The name of the source table to use for table mapping.</param> ''' <returns>The number of rows successfully updated from the System.Data.DataSet.</returns> Public Function ExecuteDataset(ByVal insertCmd As SqlCommand, ByVal updateCmd As SqlCommand, ByVal deleteCmd As SqlCommand, ByVal ds As DataSet, ByVal srcTable As String) As Integer Dim connection As SqlConnection = Nothing Dim sqlda As SqlDataAdapter = Nothing Dim res As Integer = 0 Try connection = New SqlConnection(_connectionString) sqlda = New SqlDataAdapter If Not (insertCmd Is Nothing) Then insertCmd.Connection = connection : sqlda.InsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmd.Connection = connection : sqlda.UpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmd.Connection = connection : sqlda.DeleteCommand = deleteCmd res = sqlda.Update(ds, srcTable) Catch ex As Exception Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally If Not (connection Is Nothing) Then connection.Dispose() If Not (insertCmd Is Nothing) Then insertCmd.Dispose() If Not (updateCmd Is Nothing) Then updateCmd.Dispose() If Not (deleteCmd Is Nothing) Then deleteCmd.Dispose() If Not (sqlda Is Nothing) Then sqlda.Dispose() End Try Return res End Function

#End Region

#Region " ExecuteScript "

''' <summary> ''' Executes a SQL query file against the connection. ''' </summary> ''' <param name="filename">SQL query file name.</param> ''' <param name="parameters">The parameters of the SQL query file.</param> Public Sub ExecuteScript(ByVal filename As String, Optional ByVal parameters() As SqlParameter = Nothing) Dim fStream As FileStream = Nothing Dim sReader As StreamReader = Nothing Dim connection As SqlConnection = Nothing Dim command As SqlCommand = Nothing Try fStream = New FileStream(filename, FileMode.Open, FileAccess.Read) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connection.CreateCommand() connection.Open() While (Not sReader.EndOfStream) Dim sb As New StringBuilder While (Not sReader.EndOfStream) Dim s As String = sReader.ReadLine If (Not String.IsNullOrEmpty(s)) AndAlso (s.ToUpper.Trim = "GO") Then Exit While End If sb.AppendLine(s) End While command.CommandText = sb.ToString command.CommandType = CommandType.Text AssignParameters(command, parameters) command.ExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(ex.Message, ex.InnerException) Finally

Page 22: Meo vat VB.Net

If (Not IsNothing(connection)) AndAlso (connection.State = ConnectionState.Open) Then connection.Close() If (Not IsNothing(command)) Then command.Dispose() If (Not IsNothing(sReader)) Then sReader.Close() If (Not IsNothing(fStream)) Then fStream.Close() End Try End Sub

#End Region

End Class

End Namespace

SQLDataProvider Class Documentation

This class provides a fast and universal method for accessing SQL Server database.

Create Instance

At first you create an instance of SqlDatabase class.

Dim sqldb As New SqlDatabase("Data Source=(local); Initial Catalog= ; UId = ; Pwd = ;")

For more information about connection strings, visit ConnectionStrings.com.

ExecuteNonQuery Method

Executes a Transact-SQL statement against the connection and returns the number of rows affected.

Dim params(0 To 1) As SqlParameterparams(0) = New SqlParameter("@Firstname", SqlDbType.NVarChar, 120)params(0).Value = "Stefan"params(1) = New SqlParameter("@Lastname", SqlDbType.NVarChar, 120)params(1).Value = "Cameron"sqldb.ExecuteNonQuery("Insert Into dbo.Users(Firstname, LastName) Values(@FirstName, @LastName)", CommandType.Text, params)

If you are using stored procedure,you can execute that without declaring parameters such as following code:

sqldb.ExecuteNonQuery("dbo.CreateUser", Nothing, "Stefan", "Cameron")

ExecuteScalar Method

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Dim count As Integer = sqldb.ExecuteScalar("Select Count(*) From dbo.Users", CommandType.Text) MsgBox("Number of row(s): " & count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader.

Dim FirstName As String = String.Empty Dim LastName As String = String.Empty

Dim params(0) As SqlParameter

Page 23: Meo vat VB.Net

params(0) = New SqlParameter("@Id", SqlDbType.Int) params(0).Value = 1

Dim dr As IDataReader = sqldb.ExecuteReader("Select * From dbo.Users Where (Id = @Id)", CommandType.Text, params) While dr.Read()     FirstName = dr("Firstname")     LastName = dr("Lastname") End While dr.Close()

MsgBox(FirstName & " " & LastName, MsgBoxStyle.Information)

There is a sample for using stored procedure:

Create Procedure [dbo].[GetUserInfo]     (         @Id int     ) As Begin     Select * From dbo.Users Where (Id = @Id) End

Dim FirstName As String = String.Empty Dim LastName As String = String.Empty

Dim dr As IDataReader = sqldb.ExecuteReader("dbo.GetUserInfo", Nothing, 1) While dr.Read()     FirstName = dr("Firstname")     LastName = dr("Lastname") End While dr.Close()

MsgBox(FirstName & " " & LastName, MsgBoxStyle.Information)

Using Return Value Parameter

If you are using stored procedure,you can get the value of 'return value parameter'.

Create Procedure dbo.UserExists    (        @Firstname nvarchar(120),        @Lastname nvarchar(120)    )AsBegin    If Exists(Select * From dbo.Users Where (Firstname = @Firstname) And (Lastname = @Lastname))        Return 1End

Dim retval As Integersqldb.ExecuteNonQuery("dbo.UserExists", retval, "Stefan", "Cameron")MsgBox("User Exists: " & IIf(retval = 1, "Yes", "No"))

FillDataset Method

Page 24: Meo vat VB.Net

Adds or refreshes rows in the System.Data.DataSet to match those in the data source using the System.Data.DataSet name, and creates a System.Data.DataTable named "Table."

Binding a DataGridView with FillDataset method.

DataGridView1.DataSource = sqldb.FillDataset("Select * From dbo.Users", CommandType.Text).Tables(0)

ExecuteDataset Method

Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the System.Data.DataSet with the specified System.Data.DataTable name.

' Getting the System.Data.DataSet.Dim ds As DataSet = CType(DataGridView1.DataSource, DataTable).DataSet

' Declaring insert command objectDim inscmd As New SqlCommand("Insert Into dbo.Users(Firstname, Lastname) Values(@Firstname, @Lastname)")With inscmd    .CommandType = CommandType.Text    .Parameters.Add(New SqlParameter("@Firstname", SqlDbType.NVarChar, 120)).SourceColumn = "Firstname"    .Parameters.Add(New SqlParameter("@Lastname", SqlDbType.NVarChar, 120)).SourceColumn = "Lastname"End With

' Declaring update command objectDim updcmd As New SqlCommand("Update dbo.Users Set Firstname = @Firstname, Lastname = @Lastname Where (Id = @Id)")With updcmd    .CommandType = CommandType.Text    .Parameters.Add(New SqlParameter("@Id", SqlDbType.Int)).SourceColumn = "Id"    .Parameters.Add(New SqlParameter("@Firstname", SqlDbType.NVarChar, 120)).SourceColumn = "Firstname"    .Parameters.Add(New SqlParameter("@Lastname", SqlDbType.NVarChar, 120)).SourceColumn = "Lastname"End With

' Declaring delete command objectDim delcmd As New SqlCommand("Delete From dbo.Users Where (Id = @Id)")With delcmd    .CommandType = CommandType.Text    .Parameters.Add(New SqlParameter("@Id", SqlDbType.Int)).SourceColumn = "Id"End With

' Updating data sourcesqldb.ExecuteDataset(inscmd, updcmd, delcmd, ds, ds.Tables(0).TableName)

This code will put in a TAB CHARACTER into any TEXT STRING such as a MenuItems Caption, a MsgBox, etc.. For Example if you've defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) you wouldn't want to use VB's Menu Editor

Page 25: Meo vat VB.Net

Shortcuts option for every MenuItem (since you already have the shortcuts defined). So now all you have to do is let the user know what menuitem has what shortcut. But you want the Shortcuts to be displayed one tab character after the Title Caption of the MenuItem. To do this successfully we use: Chr$(vbKeyTab)The Chr$() function is a built in function that gets an integer value passed into the parameter. However to put in the Tab Characters integer (9), it would return the number 9 and not the Tab Character. So we pass vbKeyTab to this parameter and voila.'Example using a MenuItem and a MsgBox'The MenuItem is Named mnuFileOpen'The MenuItems Caption property will get put into the'Form's Load Event

Private Sub Form_Load()mnuFileOpen.Caption = "Open" & Chr$(vbKeyTab) & "Ctrl+O"End Sub

'Define the KeyCode and Shift Integers for mnuFileOpenPrivate Sub Form_KeyDown(KeyCode As Integer, _Shift As Integer)Select Case ShiftCase 2 'If the Ctrl Key is pressed If KeyCode = vbKeyO Then 'If the "o" Key is pressed Call mnuFileOpen_Click End IfEnd SelectEnd Sub

'Define the mnuFileOpen_Click() eventPrivate Sub mnuFileOpen_Click()'Actions to perform when the File/Open MenuItem'is Clicked'ExampleMsgBox "Here is a Message Box using the Tab Character" & vbCrLf & Chr$(vbKeyTab) & "What's up Doc!"End Sub

Opening a Form by Type or Namehttp://vbcity.com/forums/faq.asp?tid=33930

Page 26: Meo vat VB.Net

Seen this question a couple of times: how to create an instance of a form if it is not know in advance which formtype has to be opened.

If you want to skip the chitchat: the .NET code example is at the end of this post

First the symantics: when we create a new form, this form has a name. If we refer to that name, we actually refer to the name of the type of object that is just created.

When to use Of course when reading the subject you might think: why not just pass the form to a parameter that takes a form (or control/object)?

The answer is: you don't when it is not sure, when or if a new instance of the object has to be created or, as mentioned, when the procedure is called it is not known which class has to be created.

You could of course hold a bunch of created objects, but that would be a shameless misuse of memory.

Imagine the following scenario (seen something like this in a post, but can't find it anymore):

You have a class that is able to trap an event, say the doubleclick of a textbox, and has to open a form when it occurs. If it's always the same form, that's easy, but what if you want it to be determined during runtime? This is a quite common story: doubleclick on article opens the detail form of that article, doubleclick on supllier opens that particular form. If you use a form variable, how do you say to the class which form should be opened? This will not work

Code: Dim FormToOpen as Form 'you don't want to open it right away, you want to know when the time comes what form to open FormToOpen = Form1

You could say FormToOpen = new Form1, but then 1. an instance would be immediately created, even if it never will be used: memory leak. 2. you can never close the form, you'll always have to use the same instance created when setting the form. Consequently, you can never open more than 1 instance using this way.

The solution: use the type. If you know the type, the Activator class will enable you to open (and return) an instance of that form at any time and as much times as you like. (The Activotor class exposes the function CreateInstance which returns an instance of the specified object) The following code creates an instance of the type form1 and shows it.

Code: CType(Activator.CreateInstance(GetType(Form1)), Form).Show()Or for better readability, the same code split up:Code:

        Dim FormToOpen As Type         FormToOpen = GetType(Form1)         Dim frm As Form = CType(Activator.CreateInstance(FormToOpen), Form)         frm.Show()

Looking back: VB6 In vb6 we could add a form with:

Code: 'VB6 Dim FormName as String

Page 27: Meo vat VB.Net

FormName = "Form1" Forms.Add(FormName).Visible = True

.NET by Type Although there are ways in .NET to create the object by its name, the removal of the form will not generate an error during compiling. But when the code is executed an exception will of course be thrown at the unsuspecting innocent user. If you refer to the type directly you can avoid this from happening.

Code: 'the straightforward version: open a form on the click of a button, the functionality can also be reached with using a forms parameter Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click     Bla(GetType(Form2)) End Sub

Sub Bla(ByVal T As Type) 'of course it's also possible to send the form and get the type at this end     Dim F As Form = Activator.CreateInstance(T)     F.Visible = True End Sub

'a more 'realistic' example. To do the same using form objects. All objects would have to be created beforehand and could only be generated once. Sub DisplayRandomForm()     Dim TypeArray() As Type = {GetType(Form1), GetType(Form2), GetType(Form3)} 'etc,etc     Randomize()     Dim Index As Integer = New Random().Next(3)     CType(Activator.CreateInstance(TypeArray(Index)), Form).Show End Sub

.NET by Name This can sometimes be necessary. For example when reading from a textfile (which for instance has a setting 'Startform'), but when possible I'd strongly recommend using the type method above to avoid runtime errors.

The only difference at the end is that you have to find the type corresponding to the specified name. This can be done with Type.GetType() (Not the same as 'normal' GetType) with which you can find the type specified by name. You will have to add the complete namespace of the object to have a valid value returned, which is where the possible difficulty begins: the namespace doesn't have to be the same as the namespace from where the code is being executed. When creating something like a textfile, or storing in a database, make absolutely sure you include the full namespace, eg "YourProject.Form1". When including the full namespace, you can simply use Type.GetType as shown in the following functionCode:

    Function GetFormByName(ByVal FormName As String) As Form         Dim T As Type = Type.GetType(FormName,True,True)         Return CType(Activator.CreateInstance(T), Form)     End Function

'an example call: GetFormByName("Form2").Show

The following code might work for some default namespaces in case the full typename wasn't provided:

Page 28: Meo vat VB.Net

Code:

    Function GetFormByName(ByVal FormName As String) As Form

        'first try: in case the full namespace has been provided (as it should )         Dim T As Type = Type.GetType(FormName, False)         'if not found prepend default namespace         If T Is Nothing Then             Dim Fullname As String = Application.ProductName & "." & FormName             T = Type.GetType(Fullname, True, True)         End If         Return CType(Activator.CreateInstance(T), Form)     End Function

But a safer way is to provide the full namespace and otherwise to search for the type. The following code will search all assemblies for the first type that corresponds with the name.Code:

Imports System.Reflection

Public Class FormFunctions     Public Shared Function GetFormByName(ByVal FormName As String) As Form

        'first try: in case the full namespace has been provided (as it should )         Dim T As Type = Type.GetType(FormName, False)         'if not found, search for it         If T Is Nothing Then T = FindType(FormName)         'if still not found, throw exception         If T Is Nothing Then Throw New Exception(FormName + " could not be found")         Return CType(Activator.CreateInstance(T), Form)     End Function #Region "Assemblies and types"     Public Shared Function GetAllAssemblies() As ArrayList         Dim al As New ArrayList         Dim a As [Assembly] = [Assembly].GetEntryAssembly()         FillAssemblies(a, al)         Return al     End Function

    Private Shared Sub FillAssemblies(ByVal a As [Assembly], ByVal al As ArrayList)         If Not al.Contains(a) Then             al.Add(a)             Dim an As AssemblyName             For Each an In a.GetReferencedAssemblies()                 If Not an.Name.StartsWith("System") Then FillAssemblies([Assembly].Load(an), al)             Next         End If     End Sub

    Public Shared Function GetAllTypes() As ArrayList         Dim a As [Assembly], t As Type, al As New ArrayList         For Each a In GetAllAssemblies()             For Each t In a.GetTypes                 If Not al.Contains(t) Then al.Add(t)             Next         Next         Return al     End Function

    Public Shared Function FindType(ByVal Name As String) As Type         Dim T As Type

Page 29: Meo vat VB.Net

        For Each T In GetAllTypes()             If T.Name = Name Then Return T         Next         Return Nothing     End Function #End Region End Class

'example call: Dim f As Form = FormFunctions.GetFormByName("Form1") f.Show()

How To Print a Formhttp://vbcity.com/forums/faq.asp?tid=28614

Difficulty Level : Intermediate

This is how you can take a picture of the form and print it.

First thing you have to do is add a PrintDocument component to the form. You can get that from the Toolbox (way down the list).

Then you need to add a PrintDialog to the form as well. Also a button that says "Print" is probably a good idea...

Code: 'We declare this here, cause were going to take the picture befor we show the print dialog 'I tried to take the picture in the PrintPage sub but it didnt work, would print the dialogs, etc. 'So we take the picture when the user presses the button, then show the dialog. Private Print_Image As Image

'This is used to take the picture Declare Auto Function BitBlt Lib "GDI32.DLL" ( _     ByVal hdcDest As IntPtr, _     ByVal nXDest As Integer, _     ByVal nYDest As Integer, _     ByVal nWidth As Integer, _     ByVal nHeight As Integer, _     ByVal hdcSrc As IntPtr, _     ByVal nXSrc As Integer, _     ByVal nYSrc As Integer, _     ByVal dwRop As Int32) As Boolean

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click

    'We make the form look pretty before its picture     Application.DoEvents()     Me.Refresh()     Application.DoEvents()          'Get a Graphics Object from the form     Dim FormG As Graphics = Me.CreateGraphics          'Create a bitmap from that graphics     Dim i As New Bitmap(Me.Width, Me.Height, FormG)          'Create a Graphics object in memory from that bitmap     Dim memG As Graphics = Graphics.FromImage(i)     

Page 30: Meo vat VB.Net

    'get the IntPtr's of the graphics     Dim HDC1 As IntPtr = FormG.GetHdc     Dim HDC2 As IntPtr = memG.GetHdc          'get the picture     BitBlt(HDC2, 0, 0, Me.ClientRectangle.Width, Me.ClientRectangle.Height, HDC1, 0, 0, 13369376)          'Clone the bitmap so we can dispose this one     Me.Print_Image = i.Clone()          'Clean Up     FormG.ReleaseHdc(HDC1)     memG.ReleaseHdc(HDC2)     FormG.Dispose()     memG.Dispose()     i.Dispose()

    'Show the PrintDialog     PrintDialog1 = New PrintDialog()     PrintDialog1.Document = PrintDocument1          Dim r As DialogResult = PrintDialog1.ShowDialog          If r = DialogResult.OK Then         'Print the document         PrintDocument1.Print()     End If

End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

    'Now we draw the image to the PrintDocument's Graphics object     'the 0 and 0 are where on the page it will be printed     '0, 0 makes it print in the top left corner of the page     e.Graphics.DrawImage(Me.Print_Image, 0, 0)

End Sub

Sample application attached.

Attachment: Print the Form.zip (15 KB)

Muon' xem moi. nguoi` dung` mo hin`h layer nhu* the' nao` , chi tiet' ^^ .

Em thuong` dung` la` mo hin`h

Kernel DataAccessBussiness User Control Presentation

Cho cac' project co' tuong tac' Database Trong Kernel se~ co' cac' lop' go^c' va` chuan? cua? ung' dung. , vi' du. nhu*SqlBase OdbcBaseetc....

Page 31: Meo vat VB.Net

ModuleBase XmlBaseCommon AppExceptionetc...

cac' lop' nay` la` cac' lop' chi? nhan. cac' tham so' , va` duoc. cac' lop' phia' sau ke' thua` . Common la` lop' chua cac' ham` static dung` chung getConnection()  tra? ve` connection readConnfig(configName) doc config trong file config encrypt()decrypt()...AppException la` lop' ke' thua` tu` Exception , moi. Exception trong ung' dung. se~ duoc. throw new cai' nay` , roi` se~ bat' het' tai. ham` main , tham so' truyen` vao` la` Message , InnerException .

SqlBase la` lop' quan? ly' Sql chung nhat' , input la` 1 connection , se~ co' cac' ham` connect , disconnect, ExcuteNonReturn , FillDataSet , ,,,etc , dung` voi' connection la` Sql OdbcBase tuong tu.

XmlBase la` lop' quan ly' Xml chung , co' cac' method  Creat, Remove , Update , Read  cac Key va` Value .

Tang` DataAccess se~ viet' cac' lop' quan ly' vao` ra du~ lieu. , ke' thua` tu` SqlBase , or OdbcBase ... , moi~ mot. doi' tuong. se~ co' 1 lop' tai. day , vi' du. Student , Manager ,...etc . cac' cau lenh. Sql duoc. viet' tai. lop' nay` , va` su? dung. cac' ham` tu` lop' SqlBase de? excute .

Bussiness la` tang` tiep' theo , voi' moi~ doi' tuong. cua? DataAccess , se~ co' 1 lop' tai. Bussiness de? control , lop' nay` se~ new 1 lop' tuong ung' tai. DataAccess de? su? dung. , du~ lieu. truyen` vao` la` ca'c bien' duoc. validate , roi` truyen` xuong' cho DataAccess de? thanh` cau lenh. Sql ,

User Control la` tang` khoi? tao. cac' Modules , No' nhan. cac' du~ lieu. tu` Bussiness chuyen? len , va` fill vao` cac' Control . Moi~ module se~ su? dung. 1 so' luong. gioi' han. cac' control , vi' du. modules view Student , se~ su? dung 1 listbox , 3 textBox ... gi` gi` do' , cai' user Control nay` ko can` biet' textBox la` gi` , cu' fill vao` thoi , moi~ lop' tai. tang` UserControl la` 1 module trong chuong trin`h . va` duoc. ke' thua` tu` lop' moduleBase tu` kernel , Vi' du. ung' dung. cua? em la` tao. Report quan? ly' Examination , thi` ko can` biet' giao dien. trong ra sao , duoi' kernel se~ co' 1 interface , khai bao' cac' control can` co' , va` cai' user control se~ theo do' ma` fill vao` .

Tang` tren cung` hoan toan` chi? la` giao dien. , tuan theo cai' interface kia ,

Cac'h thiet' ke' phia' tren cua? em co'  cai' loi. , do' la` em co' the? lam` da giao dien. 1 cach' de~ dang` , moi. thu' van~ hoat. dong. , mac. du` ko can` den' tang` tren cung` , tang` tren cung` chi? de? hien? thi. ma` thoi , vi` the' co' the? de~ dang` chuyen? thanh` giao dien. dong` lenh. voi' cac' ung' dung. unix . Chia viec. cho cac' coder cung~ de~ dang` , voi' moi~ modules  phan ra , nguoi` code se~ viet' 2 lop' , 1 lop' tai. DataAccess de? chay. lenh. , 1 lop' tai. Bussiness de? validate du~ lieu. . Tang` kernel va` usercontrol hoan` toan` dung` lai. duoc. . Co' the? thuc. hien. multi connection . ( trong cac' ung' dung. chuyen? doi? database tu` Access --> Sql server , rat pho? bien' tai. VN ) Voi' moi~ nguoi` viet' phan` cua? mi`nh , se~ ko biet' tang` tren co' cai' gi` , chi? duoc. dua cho 1 cai' dll duoc. bien dich tu` trang` tren. Co' the? bao? mat. thong tin ve` he. thong' .

Mong moi. nguoi` gop' y' ve` cac'h thiet' ke' cua? em ^^ .

code đệ quy duyệt toàn bộ các menu trong 1 MENUTRIP ( bất kể có bao nhiêu cấp ), bạn có thể sửa đổi đoạn code này để tạo TREE trong tree view hay GRID , tham số DT là 1 datatable chứa các menu mà người dùng được phép truy cập, nếu không tìm thấy thì menu đó sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object, ByRef DT As DataTable)    If Menu Is Nothing Then Return

Page 32: Meo vat VB.Net

     Dim mns As MenuStrip = TryCast(Menu, MenuStrip)     'if first levels     If mns IsNot Nothing Then          For I As Integer = 0 To mns.Items.Count - 1              Dim Mi As ToolStripMenuItem = mns.Items(I)              If Mi.DropDownItems.Count > 0 Then                  ScanMenu(Mi, DT)              End If          Next     Else          Dim Mi As ToolStripMenuItem = TryCast(Menu, ToolStripMenuItem)          If Mi Is Nothing Then Return          For I As Integer = 0 To Mi.DropDownItems.Count - 1              Dim subMi As ToolStripMenuItem              subMi = TryCast(Mi.DropDownItems(I), ToolStripMenuItem)              If subMi Is Nothing Then Continue For              If subMi.DropDownItems.Count > 0 Then                  ScanMenu(subMi, DT)              Else

                 Dim X As DataRow() = DT.Select(String.Format("AccessMenu='{0}'", subMi.Text))                 subMi.Visible = Not (X.Length = 0)               End If          Next     End IfEnd Sub

Đoạn mã của mình là dùng đệ quy để duyet toàn bô các item trong menu dùng để : - Vẽ cây phân quyền ( tree view hoặc dùng c1 flexgrid )- Duyet menu để phân quyen - thường là ẩn menu đó đi sửa đổi 1 chút cho khớp với dữ liệu của bạn .Chỉ áp dụng cho menutrip

Tôi cần hiển thị danh sách các đơn hàng và chi tiết từng đơn hàng trên 1 grid.  có bảng tblDonHang và tblChiTietDonHang. Thường khi lập trình ta sẽ tạo ra dataset có 2 bảng đó và đặt quan hệ Master - Detail thì việc hiện thị là dễ dàng. Dự án được xây dựng theo phương pháp hướng đối tượng --> có 2 lớp tương ứng là clsDonHang và clsChiTietDonHang. 2 lớp trên có các phương thức trả về dữ liệu là tập các object chứ không còn là các record nên tôi chưa có cách. Bác nào đã xử lý vấn đề này thì có thể giúp tôi xử lý với! help me!!!!!!!

Thông thường nếu xây dựng các lớp xử lý dữ liệu sẽ có các phương thức trả về đối tượng mang dữ liệu tương ứng.

Ví dụ trong trường hợp của bạn, tôi giả sử mỗi đối tượng TABLE ( đơn hàng, chi tiết đơn hàng) đều có các phương thức sau:FillData: lấy dữ liệu và điền dữ liệu vào đối tượng bạn cung cấp.GetData: lấy dữ liệu và trả về đối tượng tương ứng chứa dữ liệu đó.

Có thể phương thức này có dạng sau (trong trường hợp của bạn):public class ChiTietDonHangDataTable : System.Data.Table{

}public class DonHangDataTable : System.Data.Table{

Page 33: Meo vat VB.Net

}public class clsDonHang{public void FillData (DonHangDataTable donhang){}public DonHangDataTable GetData (){DonHangDataTable _donhang = new DonHangDataTable();//lấy dữ liệu ở đây// .................... return _donhang;}}public class clsChiTietDonHang{public void FillData(DonHangDataTable donhang){}public DonHangDataTable GetData(){DonHangDataTable _donhang = new DonHangDataTable();//lấy dữ liệu ở đây// .................... return _donhang;}}//Vậy trong trường hợp của bạn có thể xử lý như sau:public void InitDataSet(){

DataSet _dsDonHang = new DataSet();DonHangDataTable _dtDonHang = new DonHangDataTable();ChiTietDonHangDataTable _dtChiTietDonHang = new ChiTietDonHangDataTable();clsDonHang _objDonHang = new clsDonHang();clsChiTietDonHang _objChiTietDonHang = new clsChiTietDonHang();

_objDonHang.FillData(_dtDonHang);_objChiTietDonHang.FillData(_objChiTietDonHang);

_dsDonHang.Tables.Add(_dtDonHang);_dsDonHang.Tables.Add(_dtChiTietDonHang);

_dsDonHang.Relations.Add(new DataRelation("DonHang_ChiTietDonHang", "", ""));

//Gán vào Lưới ở đây

}

Có lẽ tôi chưa hiểu rõ ý bạn muốn trao đổi, nhưng theo như tôi hiểu là bạn muốn sử dụng các object đó với các giá trị của các property của nó lên các control, vấn đề này thì tôi thấy NET 2 đã xử lý rồi mà, bạn chứa các object đó trong một List<>, sau đó bạn chỉ việc dùng list này làm datasource này cho các control có khác gì là datatable, dataview hay datareader đâu, ngoài ra để binding theo đúng nghĩa bạn còn có thể xây dựng các phương thức để insert, update và delete nữa, nó còn có vẻ tiện hơn là sử dụng các command cho cái adapter trước kia. Thực ra

Page 34: Meo vat VB.Net

sau khi dùng cái này tôi ít khi còn sử dụng datatable, dataview ... để tương tác dữ liệu đằng UI nữa.Hitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being “clicked“. The method described below allows you to specify a default Button to submit when the user hits the enter key in a TextBox.

When you press a key on your keyboard, the js OnKeyPress event is fired. This calls a function to which we pass the id of the button associated with the TextBox. The function gets a reference to the button and simuilates a mouse-click on the Button. We perform a browser detection because IE and Netscape have different event models. The function finally returns false so that the keypress event is cancelled (otherwise a second form submit will be raised). This works with newer versions of IE/Netscape.

function clickButton(e, buttonid){       var evt = e ? e : window.event;      var bt = document.getElementById(buttonid);      if (bt){           if (evt.keyCode == 13){                 bt.click();                 return false;           }       } }

//code behind TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");

The code behind generates the following code:

<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')"  />

This causes web control Button1 to be clicked when the enter key is hit inside TextBox1.

i am taking one textBox and DataGrid. i want to fill DataGrid while typing the letter (KeyPress-Event).the coding is as follows

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

  Dim con As New SqlConnection("server=localhost;uid=sa;pwd=;DataBase=EMP")

   Dim com As SqlCommand

   Dim Ds As DataSet

   Dim Da As SqlDataAdapter

     com = New SqlCommand("SELECT * FROM EMPLOYEE ", con)

Page 35: Meo vat VB.Net

       Ds = New DataSet

       Da = New SqlDataAdapter(com)

       Da.Fill(Ds, "EMPLOYEE")

       DataGrid1.DataSource = Ds

       DataGrid1.DataBind()

       con.Close()

  End Sub

Mnh có một form với nhiều textbox nhập liệu. Để di chuyển giữa các text box thì mình đặt tabindex theo thứ tự, khi form hoạt động thì nhấn tab để di chuyển. Nhưng mình muốn người dùng khi nhấn vào phím mũi tên trên bàn phím thì cũng có tác dụng như phím tab. Vậy sự kiện bắt phím này như thế nào.Mình thấy vb.net có hỗ trợ e.keycode, e.keydata, e.keyvalues mình ko biết cách dùng 3 cái này thì khác gì nhau. Mình thấy cái e.keycode, e.keydata hình như giống nhau&nbsp;Vấn đề 2: Mình có một maskedtextbox để nhập liệu ngày tháng &nbsp;vào hiển thị dữ liệu lên datagrid. Sau đó mình muốn dữ liệu sẽ hiện lại lên maskedtextbox khi duyệt dữ liệu. Nhưng với ngày tháng vd 05/02/2003 thì khi hiện lên maskedtextbox với hàm định dạng Ctype(object, datetime) thì nó hiện lên là&nbsp; 52/20/07__Vậy phải định dạng thế nào để có thể hiển thị số 0 trước ngày tháng <10 để cho đúng dạng mm

O van de 1:Ban mo MSDN len tra tu SendKey.

Vấn đề 2:drg.Cell[xyz].ToString("dd/MM/yyyy");

Resize Control khi thay đổi độ phân giải của màn hìnhPublic Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim rec As Rectangle Dim CtlOut, CtlIn As Control For Each CtlOut In Me.Controls CtlOut.Tag = CtlOut.Top / Me.Height & ";" & CtlOut.Left / Me.Width & ";" & CtlOut.Width / Me.Width & ";" & CtlOut.Height / Me.Height & ";" & CtlOut.Font.Size / Me.Height If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOut.Controls CtlIn.Tag = CtlIn.Top / CtlOut.Height & ";" & CtlIn.Left / CtlOut.Width & ";" & CtlIn.Width / CtlOut.Width & ";" & CtlIn.Height / CtlOut.Height & ";" & CtlIn.Font.Size

Page 36: Meo vat VB.Net

/ CtlOut.Height Next End If Next Me.Height = Screen.GetBounds(rec).Height Me.Width = Screen.GetBounds(rec).Width Me.Top = 0 : Me.Left = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize Dim CtlOut, CtlIn As Control For Each CtlOut In Me.Controls ResizeControl(Me, CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOut.Controls ResizeControl(CtlOut, CtlIn) Next End If Next End Sub Private Sub ResizeControl(ByVal PaCtl As Object, ByVal ChCtl As Control) Dim ctlTag, CtlTop, CtlLeft, CtlWidth, CtlHeight, ctlFontSize As String Dim P1, P2 As Integer ctlTag = ChCtl.Tag.ToString P1 = ctlTag.IndexOf(";") CtlTop = ctlTag.Substring(0, P1) P2 = P1 + 1 P1 = ctlTag.IndexOf(";", P2) CtlLeft = ctlTag.Substring(P2, P1 - P2) P2 = P1 + 1 P1 = ctlTag.IndexOf(";", P2) CtlWidth = ctlTag.Substring(P2, P1 - P2) P2 = P1 + 1 P1 = ctlTag.IndexOf(";", P2) CtlHeight = ctlTag.Substring(P2, P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTag.Substring(P2) ChCtl.Top = PaCtl.Height * CtlTop ChCtl.Left = PaCtl.Width * CtlLeft ChCtl.Height = PaCtl.Height * CtlHeight ChCtl.Width = PaCtl.Width * CtlWidth ChCtl.Font = New Font(ChCtl.Font.Name, CSng(PaCtl.Height * ctlFontSize), ChCtl.Font.Style) End Sub End Class

Page 37: Meo vat VB.Net

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf Screen.Width <> 12000 And Screen.Height <> 9000 Then    Dim i As Long, Dai As Single, Rong As Single    Dai = Screen.Width    Rong = Screen.Height    Form1.Width = Form1.Width / (12000 / Dai)    Form1.Height = Form1.Height / (9000 / Rong)    For i = 0 To Form1.Controls.Count - 1        Form1.Controls(i).Top = Form1.Controls(i).Top / (12000 / Dai)        Form1.Controls(i).Left = Form1.Controls(i).Left / (9000 / Rong)        Form1.Controls(i).Width = Form1.Controls(i).Width / (12000 / Dai)        Form1.Controls(i).Height = Form1.Controls(i).Height / (9000 / Rong)        Form1.Controls(i).AutoSize = True    Next iEnd IfErr.ClearEnd Sub

' Ban co the thay 2 so : 12000 va 9000 bang cac gia tri khac tuong ung voi do phan giai chuan cua ban la 1024 x 800

Tạo form không thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị trí cố định trên màn hình và không thể di chuyển được. Tạo một form không-đường-viền bằng cách thiết lập thuộc tính FormBorderStyle là None. Hoặc bạn có thể hiện thực thuộc tính Moveable cho form. Bạn có thể tạo một form không-đường-viền bằng cách thiết lập thuộc tính FormBorderStyle là None. Các form thế này không thể di chuyển được. Và chúng nếu muốn có đường viền, bạn phải viết mã lệnh vẽ hoặccũng thiếu mất đường viền sử dụng hình nền. Có một cách khác để tạo một form không thể di chuyển được và form này có đường viền giống điều kiểm. Trước tiên, thiết lập các thuộc tính ControlBox, MinimizeBox, và MaximizeBox là False. Kế tiếp, thiết lập thuộc tính Text là chuỗi trống. Khi đó, form sẽ có đường viền nổi màu xám hoặc đường kẻ màu đen (tùy thuộc vào tùy chọn FormBorderStyle mà bạn sử dụng), tương tự như Button. Phần dưới đây sẽ trình bày một cách tiếp cận khác: hiện thực thuộc tính Moveable cho form (trong Visual Basic 6, form có thuộc tính Moveable, nhưng trong .NET, thuộc tính này không còn nữa). Trước tiên, chúng ta xây dựng lớp ImmoveableForm như sau (thừa kế từ [vb]System.Windows.Forms.Form):

Public Class ImmoveableForm Inherits System.Windows.Forms.Form

Private Declare Function EnableMenuItem Lib "user32.dll" _ Alias "EnableMenuItem" (ByVal hMenu As IntPtr, _ ByVal uIDEnableItem As Int32, ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = &H2

Private Const MF_BYCOMMAND As Int32 = &H0&

Page 38: Meo vat VB.Net

Private Const MF_ENABLED As Int32 = &H0& Private Const MF_GRAYED As Int32 = &H1& Private Const MF_DISABLED As Int32 = &H2&

Private Const SC_MOVE As Int32 = &HF010&

Private Const WM_NCLBUTTONDOWN As Int32 = &HA1 Private Const WM_SYSCOMMAND As Int32 = &H112 Private Const WM_INITMENUPOPUP As Int32 = &H117&

Private bMoveable As Boolean = True

Public Sub New() MyBase.New() End Sub

<System.ComponentModel.Category("Behavior"), _ System.ComponentModel.Description("Allows the form to be moved")> _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable <> Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As System.Windows.Forms.Message) If m.Msg = WM_INITMENUPOPUP Then ' Thụ lý việc hiển thị menu hệ thống. If m.LParam.ToInt32 \ 65536 <> 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(m.WParam, SC_MOVE, _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If m.Msg = WM_NCLBUTTONDOWN Then ' Không cho phép kéo rê cửa sổ bằng thanh tiêu đề. If m.WParam.ToInt32 = HTCAPTION Then Return

Page 39: Meo vat VB.Net

End If End If If m.Msg = WM_SYSCOMMAND Then ' Vô hiệu chức năng Move trên menu hệ thống. If (m.WParam.ToInt32 And &HFFF0) = SC_MOVE Then Return End If End If End If MyBase.WndProc(m) End Sub

End Class[/vb]

Để sử dụng lớp trên, bạn cần hiệu chỉnh phần mã do Visual Studio kết sinh cho form của bạn như sau (phần in đậm):

[vb]Public Class Form3 Inherits ImmoveableForm

Public Sub New() MyBase.New()

' This call is required by the Windows Form Designer. InitializeComponent()

' Add any initialization after the InitializeComponent() call.

' Vô hiệu khả năng di chuyển form của người dùng. Me.Moveable = False End Sub

' (Bỏ qua phần mã còn lại.)

End Class[/vb]

Sau đó chức năng bị vô hiệu hóa

Trích từ "Các giải pháp lập trình VISUAL BASIC .NET (tập 1)" http://www.dvpub.com.vn/dv/details.aspx?itemid=244Cách để xác minh mã số sách có hợp lệ hay không trong VB.NetXác nhận tính hợp lệ của ISBN

Bạn muốn xác minh một ISBN (International Standard Book Number: mã số sách chuẩn quốc tế) có hợp lệ hay không. Tính và kiểm tra bằng phép Mod 11.

Page 40: Meo vat VB.Net

Trong trường hợp này, bạn nhân mỗi chữ số với vị trí của nó (ngoại trừ số cuối cùng), cộng những số này với nhau, và kiểm tra phần dư của tổng chia cho 11 có trùng với chữ số cuối cùng hay không. Dưới đây là hàm mà bạn có thể sử dụng để kiểm tra ISBN: [vb]Private Function ValidateISBN(ByVal value As String) As Boolean Dim CheckSum As Integer = 0 Dim i As Integer For i = 0 To value.Length - 2 CheckSum += Integer.Parse(value.Chars(i)) * (i + 1) Next Dim CheckDigit As Integer CheckDigit = Integer.Parse(value.Chars(value.Length - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[/vb] Bạn có thể thử nghiệm hàm này như sau: [vb]If ValidateISBN("1861007353") Then ' Đây là ISBN hợp lệ. End If[/vb] Nhớ rằng phương thức này giả sử mọi dấu “-” đã bị loại khỏi chuỗi. Nếu không chắc bước này đã được thực hiện hay chưa, bạn có thể viết thêm mã để loại bỏ hoặc bỏ qua dấu “-” .

Trích từ "Các giải pháp lập trình Visual Basic .Net (tập 1)" http://www.dvpub.com.vn/dv/details.aspx?itemid=244Mã hóa password Tôi muốn mã hóa password trước khi chèn vào DB, không biêt bạn nào đã từng làm có thể giúp tôi trong code VB.NET được không?Bạn có thể dùng code sau:Code:

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncode.GetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5.ComputeHash(result) Return Convert.ToBase64String(result) End Function

Và import thêm cái này là ok: System.Security.CryptographyĐối số trong sự kiện VB.NET Trong bài này tôi xin nói về hai đối số mà có mặt trong mọi sự kiện của VB.Net. Một đối số gửi thông tin về đối tượng và một đối số gửi thông tin về hành động mà gây ra sự kiện.Hai đối số đó là sender và e. Đây là khai báo của sự kiện Click cho một nút:[HIGHLIGHT="vb"]Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click'End Sub[/highlight]Đối số sender lưu thông tin về đối tượng mà gây ra sự kiện, chúng ta sử dụng đối số này để xác định kiểu của đối tượng mà sinh ra sự kiện. Ví dụ:[HIGHLIGHT="vb"]Console.WriteLine(sender.ToString)

Page 41: Meo vat VB.Net

System.Windows.Forms.Button, Text: Button1Console.WriteLine(sender.GetType)System.Windows.Forms.Button[/highlight]Đối số thứ hai e chứa mọi thông tin mà bạn cần để xử lý sự kiện. Đối tượng e có một vài thuộc tính mà phụ thuộc vào kiểu của sự kiện và điều khiển sinh ra sự kiện. Thông tin mà bạn cần thiết để xử lý các kiểu sự kiện được truyền qua đối này.Sự kiện chuột:Dãy các sự kiện chuột xảy ra khi bạn nhấn chuột, thứ tự của chúng lần lượt là MouseDown, Click và MouseUp. Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua các điều khiển: sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vào điều khiển, dãy các sự kiện MouseMove xảy ra khi di chuột trên điều khiển, sau đó là sự kiện MouseHover và MouseLeave xảy ra khi chuột rời khỏi điều khiển. Mặc dù các sự kiện khác nhau nhưng chúng cùng gửi thông tin cho ứng dụng qua đối e và bạn có thể khai thác vài thuộc tính của đối e này để sử dụng trong chương trình của mình:Button: trả lại một hằng tượng trưng cho nút được nhấn, và nhận giá trị thuộc tập hằng kiểu liệt kê MouseButtons: Left, Middle, None, Right, XButton1, và XButton2. Hai giá trị cuối cùng dùng cho kiểu chuột năm nút và tương ứng với hai nút ở hai bên cạnh. Tuy nhiên đối e trong sự kiện Click hoặc DblClick không cung cấp thuộc tính Button vì hai sự kiện này chỉ được thực hiện với nút chuột trái.Clicks: trả về số lần chuột được nhấn và thả, chỉ nhận giá trị 1 hoặc 2.Delta: thuộc tính được dùng với chuột có nút cuộn, trả về số lần nút cuộn được quay. Bạn có thể dùng thuộc tính này để biết hộp Textbox đã được cuộn như thế nào.X,Y: trả lại toạ độ của chuột lúc chuột được nhấn hoặc được thả. Toạ độ chuột được tính theo toạ độ tương đối của điều khiển liên quan theo pixel. Nếu bạn nhận chuột ở góc trái trên của một nút thì toạ độ trả về sẽ là 0,0.Sự kiện bàn phím:Các điều khiển mà nhận các text thường có nhiều sự kiện bàn phím, ví dụ như điều khiển TextBox. Sự kiện KeyPress xảy ra khi một phím được nhấn còn sự kiện KeyDown và KeyUp xảy ra khi một phím được nhấn và thả tương ứng. Sau đây là khai báo của sự kiện KeyDown của TextBox[HIGHLIGHT="vb"]Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As_ System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDownEnd Sub[/highlight]Đối thứ hai cung cấp thông tin về trạng thái bàn phím và phím được nhấn thông qua các thuộc tính của nó.Alt, Control, Shift: ba thuộc tính trả về giá trị True/False xác định phím điều khiển tương ứng được nhấn khi phím được nhấn.KeyCode: trả về mã phím được nhấn và là một giá trị thuộc tập hằng liệt kê Keys. Tập hằng này chứa giá trị cho mọi phím, ví dụ kí tự "a" và "A" đều có mã là KeysA, mã của phím "0" bên keypad là Key0, phím F1 là KeyF1. Vài phím điều khiển như NumLock, ScrollLock, WakeUp và Sleep... luôn trả về KeyCode bằng 0KeyData: trả về giá trị long xác định phím được nhấn, nó cũng tương tự như thuộc tính KeyCode nhưng phân biệt kí tự và kí hiệu trên phím.KeyValue: trả lại giá trị cho phím được nhấn, thường thì cùng giá trị như KeyData, chỉ khác biệt ở các phím điều khiển.--------------Translate from Mastering VB.NET

Thêm, sửa trùng mã

Em muốn hỏi khi thêm dữ liệu ở bảng có khoá chính có kiểu nchar

thì khi thêm hay sửa dữ liệu có thể dẫn đến trùng mã

gây lỗi

Page 42: Meo vat VB.Net

Vậy cần phải có thủ tục kiểm tra khoá chính

thông báo nếu trùng thì không cho thêm

 nếu trùng thì không cho sửa

Trong trường hợp này Em nên sử dụng thêm một mã nữa.Mã này chính là mã sẽ thay đổi do người dùng nhập.Và trong thủ tục SQL Em viết như sau:

ALTER PROCEDURE sp_Insert_Update@ID nvarchar(15),@Ma nvarchar(15)IF  EXISTS (SELECT Ma FROM TenBang WHERE Ma=@Ma And ID<>@ID)        Begin            Insert ....        End        ELSE    Begin       Update......    End        

Để đưa dữ liệu từ bảng khác lên Combo Em làm như sau nhé

Đầu tiên Em viết một thủ tục bằng SQL 2000 để lấy ra bảng Em cần đưa lên Combo .Chẳng hạn bảng Branch

ALTER PROCEDURE SP_Select_Branch

AS

Select * from Branch

Sau đó Em viết 2 phương thức (Thủ tục sau)

 

 Public Shared Sub ReturnDataAdapter(ByVal strSP As String,ByVal objConn As SqlConnection) As SqlDataAdapter        Try            ' Make a comman object for stored procedure            Dim cmd As New SqlCommand(strSP, objConn)            cmd.CommandType = CommandType.StoredProcedure            Dim adt As New SqlDataAdapter(cmd)            Return adt        Catch ex As Exception            MsgBox("Error :" & ex.Message.ToString, MsgBoxStyle.OKOnly, "Thong Bao

Page 43: Meo vat VB.Net

Loi")            Return Nothing        End Try    End Function

 

 '*********************************************************    'Ham dua du lieu vao combo    Public Shared Sub GetData_Into_Cbo(ByVal sqlstr As String, ByVal cboName As ComboBox, ByVal cboValue As String, ByVal cboDisplay As String, ByVal IsNull As Boolean,ByVal objConn As SqlConnection)        Try            'ket noi CSDL de lay ra dataset            Dim datAdapter As SqlDataAdapter = New SqlDataAdapter            Dim datDsCB As DataSet = New DataSet            datAdapter = ReturnDataAdapter(sqlstr,objConn )            datAdapter.Fill(datDsCB)            datAdapter.Dispose()            'Kiem tra co null hay khong             If IsNull Then  'Neu isnull=true                ' dinh nghia bien cot va dong                Dim datTable As DataTable                Dim i As Byte                Dim myDataColumn As DataColumn                Dim myDataRow As DataRow                ' tao dong cot bang                datTable = New DataTable                myDataColumn = New DataColumn                myDataColumn.DataType = Type.GetType("System.String")                myDataColumn.ColumnName = cboDisplay                'dua cot vao bang                datTable.Columns.Add(myDataColumn)                'cot thu 1                myDataColumn = New DataColumn                myDataColumn.DataType = Type.GetType("System.String")                myDataColumn.ColumnName = cboValue                'dua cot vao bang                datTable.Columns.Add(myDataColumn)                'them mot dong                myDataRow = datTable.NewRow                myDataRow(cboValue) = ""                myDataRow(cboDisplay) = ""                'dua dong vao bang                datTable.Rows.Add(myDataRow)                If datDsCB.Tables(0).Rows.Count > 0 Then

Page 44: Meo vat VB.Net

                    For i = 0 To datDsCB.Tables(0).Rows.Count - 1                        myDataRow = datTable.NewRow                        myDataRow(cboValue) = datDsCB.Tables(0).Rows(i).Item(cboValue)                        myDataRow(cboDisplay) = datDsCB.Tables(0).Rows(i).Item(cboDisplay)                        'dua dong vao bang                        datTable.Rows.Add(myDataRow)                    Next                End If                'Dua bang vao Dataset                datDsCB.Tables.Add(datTable)                'gan gia tri nguon cho Combo                cboName.DataSource = datDsCB.Tables(datTable.TableName)            Else  'Neu khong null                'gan gia tri nguon cho Combo                cboName.DataSource = datDsCB.Tables(0)            End If            'cot dua vao gia tri nho cua combo            cboName.ValueMember = Trim(cboValue)            ' dua  dl tu cot de hien thi tren combo            cboName.DisplayMember = Trim(cboDisplay)        Catch ex As Exception            MsgBox(ex.ToString)        End Try    End Sub

 

Trên Form Em goi như sau

GetData_Into_Cbo("SP_Select_Branch",cboBranch,"BranchID","BranchName",False,Conn)

Trong đó : SP_Select_Branch là tên thủ tục Em viết trong SQL,cboBranch là tên Combo,Conn là đối tượng kết nối

Bạn đã tạo được giao diện XP trong VB.NET 2003 chưa? Chắc là chưa đúng không?

Nếu chưa tạo được bạn hãy làm theo các bước sau đây đảm bảo sẽ có giao diện XP

Sau khi bạn kéo và thả các đối tượng vào Form bạn vào Properties tiếp đến bạn chọn thuộc tính FlatStyle là System (Tất nhiên sẽ có một số đối tượng không có thuộc tính này ví dụ như ComboBox chẳng hạn ,nhưng mình không cần quan tâm nó sẽ tự động nhận)

Sau đó bạn tải File   XP.EXE.manifest  rồi đổi tên XP thành tên dự án của bạn và vất vào thư mục chứa File .EXE là xong.

Page 45: Meo vat VB.Net

Cụ thể là : Giả sử dự án của bạn tên là  KT  (KT là tên hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XP.EXE.manifest  thành  KT.EXE.manifest  rồi vất vào thư mục chứa .EXE.

Như vậy bạn sẽ có giao diện XP

File đính kèm(s):XP.EXE.manifest (1kb) Tải 124 lần(s)

Thay oi tai sao moi lan em cap nhat du lieu thi tren C1flexgrid ko tu dong cap nhat a. Em co viet cau lenh: tenluoi.refesh() nhung cung ko nhan. Co can phai viet them doan lenh nao ko a?

Em dùng câu lệnh tenluoi.refesh() thì chưa đủ đâu

 Em chỉ cần gọi lại phương thức (thủ tục) GetDataGird() sau khi cập nhận dữ liệu thành công là xong

GetDataGird()  nằm trong sự kiện khi click chuột vào nút Cập nhật Em a.Trong VB.NET việc đưa dữ liệu ra DataSet thì quả là đơn giản đúng không ?.Những liệu bạn đã biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thông tin cần thiết chưa?.Điều này thì chắc không phải ai cũng biết.

Tối lấy một trường hợp thế này.Giả sử tôi có một DataSet chứa dữ liệu của bảng KhachHang với các trường MaKH,TenKHBây giờ tôi muốn lấy ra những khách hàng có mã >10 .Đây chính là truy vấn dữ liệu trong DataSet

Tôi xin giới thiệu với chúng ta một cách làm như sau:

Sau khi đưa dữ liệu ra DataSet bằng câu lệnh

Dim da As SqlDataAdapterDim ds As DataSet=New DataSet........da.Fill(ds,"KhachHang")Chúng ta làm như sau:

Đầu tiên chúng ta khai báo một DataRow

Dim RowMaKH As DataRow()RowMaKH= ds.Tables("KhachHang").Select("MaKH >10")

Như vậy RowMaKH sẽ chứa toàn bộ những khách hàng có mã >10

Page 46: Meo vat VB.Net

Để lấy giá trị thứ i trong RowMaKH bạn chỉ cần dùng câu lệnh RowMaKH(i).Item("MaKH")cach nao de co combobox tren luoi flexgridCó hai trường hợp xảy ra.

Một do người dùng định nghĩa và tạo thành ComboBox. Giả sử Thầy muốn tạo ra combobox có nam và nữ.Trường hợp này ta làm như sau:

            Dim slist As SortedList            slist = New SortedList            slist.Add("True", "Nam")            slist.Add("False", "Nữ")            GirdName.Cols("TenCot").DataMap = slist

Trường hợp 2 .Lấy từ cơ sở dữ liệu ra thành combobox

Trường hợp này sẽ làm như sauĐầu tiên viết một hàm

'*****************************************************    'ham truyen gia tri vao cac Sortedlist de dua vao cac cbo cua luoi Public Shared Function Add_Data_Grid(ByVal strSqlStore As String, ByVal sKey As String, ByVal sValue As String) As SortedList        Dim datSqlAdapter As SqlDataAdapter        Dim i As Integer        Dim datDs As DataSet        'khoi tao mot SorttedList        Dim slist As SortedList = New SortedList        Try            slist = New SortedList            datSqlAdapter = New SqlDataAdapter            datDs = New DataSet            datSqlAdapter = ReturnDataAdapter(strSqlStore)            datSqlAdapter.Fill(datDs, "cboTable")            datSqlAdapter.Dispose()            If datDs.Tables("cboTable").Rows.Count > 0 Then                For i = 0 To datDs.Tables("cboTable").Rows.Count - 1                    slist.Add(Trim(datDs.Tables("cboTable").Rows(i).Item(sKey).ToString), Trim(datDs.Tables("cboTable").Rows(i).Item(sValue)))                Next            End If            datDs.Dispose()            Return slist        Catch ex As Exception            MsgBox(ex.ToString)            datDs.Dispose()

Page 47: Meo vat VB.Net

        End Try    End Function

Trong code ta gọi như sau

 Dim slist As SortedList  slist = New SortedList  slist = Add_Data_Grid("sp_Select", "ID", "Name")  GrdName.Cols("TenCot").DataMap = slist'sp_Select là cau sql lay du lieu tu bang

Các đoạn này sẽ được đặt sau GetDataGird() và trong FormatGird() Em thêm câu lệnh GirdName.AllowEditing=True

lam the nao de bat loi duoc nguoi dung a

vi du nguoi dung co tinh khong nhap ngaysinh chang han thi ta phai thong bao de ho nhap du thi moi cho luu

va nguoi dung nhap gia tri vao truong khoa ngoai ma chua co gia tri nay o truong khoa chinh cua bang khac thi  bi loi chuong trinh

vay lam sao de kiem soat  van de nay

Thứ nhất : Đối với dữ liệu ngày, tháng Em không nên dùng đối tượng TextBox mà nên dùng đối tượng DateTImePicker .Mặc định sẽ có dữ liệu ngày tháng, Nếu cố tình không nhập thì vẫn có.Còn nếu Em  dùng TextBox thì chỉ cần kiểm tra . If TextBox.Text="" then    MessageBox.Show("Bạn chưa nhập ngày sinh")

Thứ 2. Để kiểm soát được vấn đề khoá ngoại và khoá chính như vậy thì rất đơn giản Em làm như sau nhé

Em xem trường khoá ngoại đó có cho phép Null hay không.Nếu cho phép Null thì không cần quan tâm đến trường khoá chính có dữ liệu hay không.Còn nếu không cho phép Null thì khi Em dưa dữ liệu từ bảng có khóa chính lên Combo để chọn thì Em mặc định cho Combo có dữ liệu là xong.Kể cả khi người dùng không chọn thì mặc định vẫn có dữ liệu .lam the nao de co checkbox hien len tren luoiTuỳ thuộc vào cột nào Em cần có CheckBox thì Em sẽ cho làm CheckBox và chỉ cần dùng thuộc tính .DataType

Ví dụ Em cần cho cột  GioiTinh là CheckBox Em dùng câu lệnh

GrdName.Cols("GioiTinh").DataType=GetType(Boolean)GrdName.Cols("GioiTinh").AllowEditing=True

GrdName : là tên lưới

Page 48: Meo vat VB.Net

GioiTinh : Là cột cần là CheckBox

Đoạn Code trên Em cho vào phần  FormatGird()Lam sao em tao truong ngay thang  len luoi ko duoc (tren luoi ko co truong ngay thang)Đúng vậy trên lưới không có trường ngày tháng.Để có trường ngày tháng Em phải viết một đoạn Code .Đoạn code này sẽ nằm trong phần FormatGird().

Tuỳ thuộc vào cột nào  Em muốn cho là ngày tháng mà viết code tương ứng và dùng thuộc tính .DataType.

Ví dụ Em muốn cột ngày sinh (NgaySing) là ngày tháng.Em làm như sau

GrdName.Cols("NgaySinh").DataType=GetType(DataTime)GrdName.Cols("NgaySinh").AllowEditing=TrueGrdName : Là tên lướiNgaySinh : Là cột ngày sinh sẽ hiện trên lưới

1. Em muốn hỏi ta có bảng Khoa có mã khoa là duy nhất không trùng

 làm thế nào sau khi thêm nếu trùng mã khoa

thì thông báo mã khoa này đã tồn tại rồi

2. Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nào ạ

3. Code chương trình phải sửa như thế nào ạ

Để làm được điều  này thì trong thủ tục  sp_Insert_Update_mFaculty  Em thêm một tham số @KT  như sau

sp_Insert_Update_mFaculty   @ma int,   ........  @KT bit output

AS      IF EXISTS(SELECT * FROM TenBangWHERE ma=@ma)            Begin                   Update .......                  SET @KT=0            End   ELSE             BEGIN                                   Insert ........                                        SET @KT=1

Page 49: Meo vat VB.Net

             END

Trong Code cung thêm một tham số @KT như sau

Dim Param as SqlParameter() ={ New  .......                                                              New SqlParameter("@KT",SlqDataType.Bit)}

Param(0).Value=........Param(5).Direction=ParameterDirection.Output   ''''Tham số @KT  giả sử là thứ 5

  RunSP("sp_Insert_Update_mFaculty ",cnn,Param)

If  Param(5).Value=True then   MessageBox.Show("Mã bạn vừa nhập đã tồn tại.Đề nghị bạn nhập mã khác")End If

Làm thế nào mà khi Nhấn vào tìm kiếm nếu thấy thì

Lưới nhảy đến dòng tìm thấy và các ô textbox nhảy theo

Em đã thử rồi chỉ làm được với textbox nhưng lưới không được

Để làm được điều này Em chỉ cần dùng thuộc tính  .Select là được. Cụ thể như sau

If  txtHoTen.Text<>"" then   For i as integer=0 to grdName.Rows.Count -1                If txtHoTen.Text=grdName(i,"HoTen") then                      grdName.Select(i,True)        'Dòng tìm thấy được chọn                End If    NextEnd if

Khi có lệnh grdName.Select(i,True) này lập tức các TextBox trên Form sẽ hiển thị dữ liệu tương ứng trên lưới thông qua sự kiện           grdName_EnterCell()

Em muốn hỏi tại sao Khi chạy Form Login thanh thực đơn UltraToolBar không hiện chỉ khi ta đóng Form Login nó mấy hiện

Em đã Cho thuộc tính ToMost của Form Login bằng True

Và trong thủ tục Load của Form Main em gọi Form Login

Page 50: Meo vat VB.Net

Nhưng không hiểu tại Sao Thực đơn UltraToolBar vẫn không hiện chỉ khi đóng Form nó mới hiện

Trong UltraToolBar em đã đặt thuộc tính IsMenuBar là True

Và Trong Form Main Em đã đặt thuộc tính Là Form Chính

Không hiểu sao lại không được

Vậy Em thử thế này nhé

Trong form Main khi Em gọi form Login Em dùng thuộc tính Show() thay cho ShowDialog()

frmLogin.Show()

em tao 1 panel va ben trong  co 1 dockmanager (lam menu doc tren MDI form)

Nhung khi chay chuong trinh thi nguoi dung co the click chuot phai vao man hinh MDI de add Group hoac xoa Group

Va co the thay doi do rong cua panel vay lam the nao de kiem soat viec nay

Thực ra việc Add Group hoặc xóa Group kể cả thêm Button hoặc Toolbar khi Click chuột phải vào thực chất chỉ là ảo.Tức là những công việc đó chỉ tồn tại và có hiệu lực trong thời gian mình chạy phần mềm thôi và khi mình thoát phần mềm rồi chạy lại thì những mục mình đã  Thêm ,Xoá  vẫn tồn tại.

Em thử chạy Office 2003 mà xem .Nó cũng cho mình thêm,xóa các mục trên menu những khi chạy lại thì vẫn còn những cái mình đã xoá.

Mình nên để người dùng thay đổi Panel Em ạ. Vì khi độ phân giải màn hình thay đổi thì Panel sẽ được thay đổi theo.Nếu mình quản lý nó không cho nó thay đổi thì không hay đâu.

Việc quản lý Thêm , xóa cũng có thể quản lý được nhưng mình cứ để cho người dùng thêm xóa không sao Em ạ.

em chua cach dung "byref",trong lap trinhem toan dung "byval",nhung co mot so sach emdoc thay co dung "byref",em thay no chang khac gi "byval",thay co the noi ro hon de em phan biet ,va thay cho em vi du ve 1 ham nhung dung trong 2 truong hop,1 truong hop dung "byval",1 truong hop dung "byval"

Trong VB.NET có 2 cách truyền các tham số vào các phương thức (Thủ tục hoặc hàm) là ByVal (Truyền theo tham trị) và ByRef (Truyền theo tham chiếu) .Hai cách dùng này hoàn toàn khác nhau chứ không phải giống nhau như Em nghĩ và trong VB.NET mặc

Page 51: Meo vat VB.Net

định khi lập trình viên truyền các tham số vào các phương thức nó sẽ là ByVal .Thông thường thì nên dùng ByVal .

Em để ý ví dụ sau thì sẽ hiểu nhé

Private FunctionTinhTong(ByVal a As Integer,ByVal b As Integer) As Interger   Return a+bEnd Function

Private Sub ThayTheByVal(ByVal C As Integer)Dim i As Integer =5C=iEnd Sub

Private Sub ThayTheByRef(ByRef C As Integer)Dim i As Integer =5C=iEnd Sub

Dim Tong As Integer=0

Tong=TinhTong(5+5)

Nếu là ByVal thì sau khi gọi    ThayTheByVal(Tong)   thì kết quả vẫn là 10  Nhưng nếu là ByRef thì sau khi goi ThayTheByRef(Tong)   thì kết quả lại là 5

Em đọc kỹ rồi sẽ hiểu.  Tóm lại là .Khi truyền bằng ByVal  thì  nó sẽ không bị thay đổi bên trong phương thức còn khi truyền bằng ByRef thì nó sẽ bị thay đổi bên trong phương thức

Thầy cho em hỏi các nút di chuyển ( Về đầu , Về Cuối , Về Trước , Về Sau và cả nút Huỷ bỏ thao tác nữa ) phải viết code cho no thế nào ?

Em viết như sau nhưng không được :

Me.BindingContext(ds.Tables("mSchool")).Position=0    ' Về đầu

Me.BindingContext(ds.Tables("mSchool")).Position - = 1    ' Về trước

Me.BindingContext(ds.Tables("mSchool")).Position + = 1   ' Về sau

Me.BindingContext(ds.Tables("mSchool")).Position =   Me.BindingContext(ds.Tables("mSchool")).Count - 1  ' Về cuối

Em làm như vậy nhưng không được thầy ạ !

Page 52: Meo vat VB.Net

Em làm thế này là sai rồi .Không được là đúng rồi

Em làm như thế này nhé.

'Phương thức dùng để nhảy  xuống dòng tiếp theo

 Private Sub RowNext()          grdName.Focus()        If grdName.RowSel < grdName.Rows.Count - 1 Then   'Nếu không phải là cuối            grdName.Select(grdName.RowSel + 1, True)        Else            grdName.Select(grdName.RowSel, True)   'Nếu là cuối        End If    End SubEm dang lam bang QH,nhung khi ket noi voi CSDL thi bi thong boa loi.Vay thay hay chi cho em ve thu thuc ket noi voiQúa trình kết nối như sau

Đầu tiên Em Imports 2 thư viện  System.Data,System.Data.SqlClient

Sau đó   Dim strConn As String="Server=TenMay ; DataBase=TenDataBase ; User ID =sa ; Password=sa "   Dim ObjConn As SqlConnection=New SqlConnection(strConn)    ObjConn.Open()

em co hai bảng :

CT1

SoCT char(10) MaK char(10) NgayTT datetime SoTien float CT2 SoCT char(10) MaHang char(10) MaNV char(10) Bảng CT1 và CT2 liên kết 1-1

Trong nút lưu em viết:

dim param as sqlparameter()={new sqlparameter("SoCT",sqldbtype.char),new sqlparameter("MaK",sqldbtype.char),new sqlparameter("NgayTT",sqldbtype.datetime),new sqlparameter("SoTien",sqldbtype.float),new sqlparameter("MaHang",sqldbtype.char),new sqlparameter("MaNV",sqldbtype.char)}

param(0).value=me.txtSoCT.text

param(1).value=me.cboMaK.selectedvalue

param(2).value=me.NgayTT.text

Page 53: Meo vat VB.Net

param(3).value=me.txtSoTien.text

param(4).value=me.cboMaHang.selectedvalue

param(5).value=me.cboMaNV.selectedvalue

clsDataBase.RunSP("Insert_CT",cnn,param)

getdatagird()

-----------------------------

trong thủ tục Insert_CT:

alter proc Insert_CT

@SoCT char(10),@MaK char(1),@NgayTT DateTime,@SoTien float,@MaHang char(10),@MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(@SoCT,@NgayTT,@MaK,@SoTien)

insert into CT2 values(@SoCT,@MaHang,@MaNV)

end

if(@@err<>0)...................

---------------------------

em chạy thì nó báo lỗi:

SoCT  is not a parameter for procedure Insert_CT

---------------------

Em để ý nhé :

dim param as sqlparameter()={new sqlparameter("SoCT",sqldbtype.char),new

Page 54: Meo vat VB.Net

sqlparameter("MaK",sqldbtype.char),new sqlparameter("NgayTT",sqldbtype.datetime),new sqlparameter("SoTien",sqldbtype.float),new sqlparameter("MaHang",sqldbtype.char),new sqlparameter("MaNV",sqldbtype.char)}

Tất cả các tham số đều không có @   Em phải làm như sau:

dim param as sqlparameter()={new sqlparameter("@SoCT",sqldbtype.char),new sqlparameter("@MaK",sqldbtype.char),new sqlparameter("@NgayTT",sqldbtype.datetime),new sqlparameter("@SoTien",sqldbtype.float),new sqlparameter("@MaHang",sqldbtype.char),new sqlparameter("@MaNV",sqldbtype.char)}

Nếu không có @ chắc chắn sẽ báo  SoCT  is not a parameter for procedure Insert_CT

CT1:

SoCT char(10) MaK char(10) NgayTT datetime SoTien float

CT2:

SoCT char(10) MaHang char(10) MaNV char(10)

Thầy giúp em nha

Em không nên viết Insert vào 2 bảng bằng một thủ tục .Em nên viết bằng TRIGER thì tốt hơnThầy hướng dẫn cho em cách làm một  form tìm   kiếm sinh viên kết qủa hiện thị trên Grid (tìm kiêm theo tên trong bảng mStudents)Em đưa đoạn Code sau vào sự kiện tìm kiếm nhé:

Private Sub cmdTimKiem_Click( ByVal sender As Object , ByVal e As System.EventArgs) Handles cmdTimKiem.ClickIf grdName.Rows.Count>0  Then  'Nếu lưới có dữ liệu     If txtHoten.Text<>"" then      'Nếu họ tên không trống                  For i as integer =0 to grdName.Rows.Count-1                         If txtHoten.Text=grdName(i,"HoTen") Then   'Nếu tồn tại                                        grdName.Select(i,True)

Page 55: Meo vat VB.Net

                                        Exit Sub                         End If                   Next     End If        End If

End SubMình có 1 treeview, 1 nút cha và 1 nút con, có 2 contextmenu. Mình không biết cách làm thế nào để khi nhấn chuột phải vào nút cha thì hiện contextmenu1, nhấn vào nút con thì hiện lên contextmenu2Giải thuật là bạn bắt sự kiện MouseDown, nếu là chuột phải thì kiểm tra node dưới con trỏ chuột là parent hay child rồi show menu tương ứng.Code demo là C#, bạn chịu khó convert sang VB.EET

private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e){if (e.Button == MouseButtons.Right) // Chuột phải{TreeNode node = treeView1.GetNodeAt(e.X, e.Y);if (node == null) return;

if (node.Parent == null)this.contextMenu1.Show(treeView1, new Point(e.X, e.Y));elsethis.contextMenu2.Show(treeView1, new Point(e.X, e.Y));//MessageBox.Show(node.Parent.Text);}}khi tôi muốn sử dụng các hàm string như: right, left...thì phải khai báo không gian tên như thế nào? (System....)Bạn dùng namespace này:Imports Microsoft.VisualBasicVà gọi hàm như sau:Dim str As String = "test string"str = Microsoft.VisualBasic.Left(str, 1)Nếuimport thì không cần khai báo Microsoft.VisualBasicvà ngược lại nếu khai báo thì chỉ việc sử dụng Left(string, string_len)Tôi dùng môt file CSDL tạm để nạp dữ liệu cần in hóa đơn bán hàng. Mỗi khi in cho khách mới thì phải xóa dữ liệu đã in cho khách hàng trước đó. Nhưng làm sao để xóa nội dung file đó cho nhanh (không phải xóa từng dòng)?. Tôi sử dụng CSDL Access, sử dụng kết nối OleDb. Mong các bạn chỉ dùmNếu chương trình của bạn hỗ trợ xử lý truyền thẳng câu lệnh SQL tới DB để chạy thì bạn có thể truyền câu lệnh DELETE tới DB để xoá các record.Còn không bạn có thể làm 1 vòng lặp để xoá các record của bạn.Sử dụng kết nối và đối tượng Command thích hợp rồi truyền thằng cho nó một câu lệnh SQL:

"Delete from tên_bảng" (MySQL) các cơ sở dữ liệu khác là : "delete * from tên_bảng". Nếu bạn

muốn xóa tất cả nội dung của file đó mà không phải là xóa nội dung một bảng thì bạn truyền

câu lệnh SQL: "Drop TABLE tên_bảng" nhưng lần sau thì bạn sẽ lại phải khởi tạo lại bảng đấy.

Cảm ơn bạn! tôi cũng đã làm đựoc như vậy rồi. Nhưng có vấn đề phát sinh là cần xác định xem Table đó có tồn tại trong Database không?. Nếu Table đó ko tồn tại mà Drop Table thì sẽ báo lỗi, ngược lại nếu Table đã có mà dùng Create Table hoặc SELECT ..... INTO Table thì nó cũng báo lỗi.