55
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. Đ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. Console.WriteLine("Application: " & Name.Name)

Mẹo vặt VB.Net

Embed Size (px)

DESCRIPTION

Các mẹo vặt hay về VB.Net

Citation preview

Nhấn phiacutem Enter thigrave kiacutech hoạt phiacutem TABTrong vbnet 2003 trecircn 1 formtrong khi bạn design caacutec đ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 nhiecircn khi bạn nhấn phiacutem TAB cursor sẽ tự động nhảy đến đối tượng được tạo tiếp theo Cograven bạn nhấn enter thigrave khocircng được nếu muốn điều đoacute bạn coacute thể lagravem như saukhai baacuteo thuộc tiacutenh KeyPreview của form = TRUE Sau đoacute trong sự kiện KeyDown của formgiả sử tecircn của form đoacute lagrave frmViDu

Private Sub frmViDu_KeyUp(ByVal sender As Object ByVal e As SystemWindowsFormsKeyEventArgs) Handles MyBaseKeyUpIf eKeyCode = KeysEnter ThenSendKeysSend(TAB)End IfEnd Sub

Tạo hộp About động trong VBnetBạn muốn thu lấy thocircng tin phiecircn bản luacutec thực thi với mục điacutech hiển thị trong hộp AboutThu lấy một tham chiếu đến assembly hiện hagravenh bằng Assembly GetExecutingAssembly vagrave thu lấy AssemblyName của noacute (coacute kegravem thocircng tin phiecircn bản trong đoacute)Đối với một ứng dụng thật quan trọng khi noacutei đuacuteng phiecircn bản của noacute (vagrave đocirci luacutec coacute thecircm caacutec thocircng tin như tecircn file vagrave bản địa) magrave khocircng cần phải viết matilde cứng cho dữ liệu nagravey Cơ chế phản chiếu cung cấp một giải phaacutep lyacute tưởng vigrave noacute cho pheacutep thu lấy caacutec chi tiết nagravey một caacutech trực tiếp từ siecircu dữ liệu của assemblyĐoạn matilde dưới đacircy hiển thị vagravei mẩu thocircng tin về assembly hiện hagravenh bằng cơ chế phản chiếu Noacute cũng trigravenh bagravey caacutech thu lấy những thocircng tin đoacute một caacutech giaacuten tiếp từ lớp SystemWindowsFormsApplication (bất chấp kiểu ứng dụng lagrave gigrave)Public Module TestReflection Public Sub Main() Dim ExecutingApp As SystemReflectionAssembly ExecutingApp = SystemReflectionAssemblyGetExecutingAssembly() Dim Name As SystemReflectionAssemblyName Name = ExecutingAppGetName() Hiển thị thocircng tin siecircu dữ liệu ConsoleWriteLine(Application amp NameName)

ConsoleWriteLine(Version amp NameVersionToString()) ConsoleWriteLine(Code Base amp NameCodeBase) ConsoleWriteLine(Culture amp NameCultureInfoDisplayName) ConsoleWriteLine(Culture Code amp NameCultureInfoToString()) (Nếu assembly đatilde được kyacute bạn coacute thể sử dụng NameKeyPair để thu lấy khoacutea cocircng khai) Một số thocircng tin được lấy từ lớp Application Thocircng tin phiecircn bản lagrave giống hệt ConsoleWriteLine(Assembly File amp _ SystemWindowsFormsApplicationExecutablePath) ConsoleWriteLine(Version amp _ SystemWindowsFormsApplicationProductVersion) Thocircng tin Company vagrave Product được thiết lập thocircng qua đặc tiacutenh AssemblyCompany vagrave AssemblyProduct (thường nằm trong file AssemblyInfovb) ConsoleWriteLine(Company amp _ SystemWindowsFormsApplicationCompanyName) ConsoleWriteLine(Product amp _ SystemWindowsFormsApplicationProductName) Thocircng tin bản địa lagrave bản địa hiện hagravenh (trong trường hợp nagravey lagrave 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 nagravey lagrave khocircng coacute) ConsoleWriteLine(Culture amp _ SystemWindowsFormsApplicationCurrentCultureToString()) ConsoleWriteLine(Culture Code amp _ SystemWindowsFormsApplicationCurrentCultureDisplayName) ConsoleReadLine() End SubEnd ModuleChuacute yacute rằng GetExecutingAssembly luocircn trả về một tham chiếu đến assembly magrave matilde lệnh đang thực thi ở đoacute Noacutei caacutech khaacutec nếu bạn chạy một ứng dụng Windows (assembly A) coacute sử dụng một thagravenh phần độc lập (assembly B) vagrave thagravenh phần đoacute cho gọi GetExecutingAssembly noacute sẽ nhận được một tham chiếu đến assembly B Bạn cũng coacute thể sử dụng GetCallingAssembly (thu lấy assembly magrave lệnh gọi được định vị ở đoacute) hoặc GetEntryAssembly (trả về assembly coacute thể thực thi đối với miền ứng dụng hiện hagravenh) Assembly lagrave một từ khoacutea dagravenh riecircng trong Microsoft Visualcong Basic NET Do đoacute nếu muốn tham chiếu kiểu SystemReflectionAssembly 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 vuocircng Lệnh nagravey lagravem việcDim Asm As SystemReflectionAssembly

Lệnh nagravey cũng lagravem việc giả sử bạn đatilde nhập khocircng gian tecircn SystemReflectionDim Asm As [Assembly]

Lệnh nagravey sinh ra lỗi biecircn dịch vigrave Assembly lagrave từ khoacutea dagravenh riecircngDim Asm As Assembly

Tạo form với hiệu ứng DropShadowrất đơn giảnbạn chỉ cần khai baacuteo tham số CS_DROPSHADOW vagrave với noacute bạn coacute thể lagravem cho bất cứ Window nagraveo cũng sẽ coacute một caacutei boacuteng như dưới đacircy bằng trao cho lớp của noacute tham số trecircn

[vb]Protected Overrides ReadOnly Property CreateParams() As SystemWindowsFormsCreateParams Get Dim parameters As CreateParams = MyBaseCreateParams parametersClassStyle = parametersClassStyle 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 lagravem gigrave đoacute) vagrave thời điểm kết thuacutec 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 = DateTimeNow() timeDifference = timeEndSubtract(timeStart) timeElapsed = timeElapsedAdd(timeDifference) Return timeElapsedToString()

End Function

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

Implementation

Dim timeStart As DateTime

timeStart = DateTimeNow()

caacutec cacircu lệnh lagravem chuyện gigrave đoacute

MelblDurationText = GetDuration(timeStart)

vagrave lấy kiểu ngagravey khocircng coacute gắn giờDim _date As Date = DateTimeNowDate

SubClass trong NET Triacutenh ldquohellipWindows gửi thocircng điệp lagrave một hằng số tới caacutec form vagrave caacutec control của VB để baacuteo cho chuacuteng biết vị triacute chuột ở đacircu khi nagraveo thigrave cần vẽ lại phiacutem nagraveo đang được nhấn vagrave nhiều thocircng điệp khaacutec Kỹ thuật subclassing lagrave để xử lyacute chặn những thocircng điệp nagravey trước khi chuacuteng đến được caacutec form vagrave control Bằng caacutech chặn caacutec thocircng điệp nagravey vagrave xử lyacute vagravei thứ trước khi chuacuteng đến điacutech chuacuteng ta coacute thể coacute caacutec tiacutenh năng riecircng (như tự vẽ lại caacutec control theo yacute riecircng)Subclassing lagrave một kỹ thuật tinh vi chỉ cần một lỗi nhỏ (viacute dụ như do bạn giải phoacuteng tagravei nguyecircn khocircng tốt dẫn đến việc thất thoaacutet tagravei nguyecircn của hệ thống) lagrave coacute thể dẫn đến việc hệ thống của bạn bị thiếu tagravei nguyecircn lagravem cho hệ thống hoạt động khocircng cograven tốt nữa (chậm đi) nặng hơn lagrave VB bị shut down thậm chiacute treo maacutey Tuy nhiecircn noacutei điều nagravey lagrave để bạn yacute thức được vấn đề chứ bạn cũng khocircng necircn quaacute lo ngại về noacute Vagrave thecircm 1 chuacute yacute lagrave bạn cũng khocircng necircn bấm nuacutet stop của VB khi chương trigravenh đang chạy magrave bạn necircn đoacuteng form 1 caacutech thocircng thường (bấm nuacutet close) để thực hiện tốt việc giải phoacuteng tagravei nguyecircnhelliprdquo Trong VB6 bạn coacute thể dugraveng Kỹ thuật nagravey bằng caacutech tạo ra một Lớp vagrave dugraveng caacutec hagravem API như SetWindowLongCallWindowProchay Sendmessage vagrave một số tin nhắn Cograven trong NET bạn coacute thể bắt tin nhắn vagrave xứ liacute chuacuteng bằng caacutech dugraveng phương thức WndProc trong Form như sau [vb]Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage)

Select Case mMsg Case WM_MOUSEMOVE xử liacute tin nhắn ở đacircy End Select End Sub[vb] Nhưng caacutech dugraveng trecircn coacute một vagravei nhược điểm như một số Control khocircng coacute phương thức nagravey vagrave giống như liacute do magrave trong VB6 bạn phải tạo một lớp riecircng để SubClassVigrave vậy việc SubClass trong NET sẽ dễ dagraveng hơn khi dugraveng Lớp NativeWindowBạn coacute thể tạo bằng caacutech tạo một lớp mới vagrave thừa hưởng lại từ Lớp NativeWindow

[vb]Imports SystemRuntimeInteropServices Imports SystemDrawing Imports SystemDrawingDrawing2D

Public Class Class1 Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage) Select Case mMsg Case WM_NCACTIVATE Sứ liacute tin nhắn ở đacircy End Select MyBaseWndProc(m) End Sub End Class[vb] Caacutech dugraveng lớp nagravey như sau Trong NativeWindow coacute 3 phương thức magrave bạn dugraveng để bắt đầu với kỹ thuật SubClass trong NET 1 AssignHandle( handle as IntPtr) Gaacuten một đối tượng vagraveo handle của cửa sổ vagrave bắt đầu Subclass 2 ReleaseHandle( handle as IntPtr) Huỷ bỏ Subclass vagrave đưa giaacute trị của handle về giagrave trị 0 [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseLoad sAssignHandle(MeHandle) End Sub

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

ConsoleWriteLine(Version amp NameVersionToString()) ConsoleWriteLine(Code Base amp NameCodeBase) ConsoleWriteLine(Culture amp NameCultureInfoDisplayName) ConsoleWriteLine(Culture Code amp NameCultureInfoToString()) (Nếu assembly đatilde được kyacute bạn coacute thể sử dụng NameKeyPair để thu lấy khoacutea cocircng khai) Một số thocircng tin được lấy từ lớp Application Thocircng tin phiecircn bản lagrave giống hệt ConsoleWriteLine(Assembly File amp _ SystemWindowsFormsApplicationExecutablePath) ConsoleWriteLine(Version amp _ SystemWindowsFormsApplicationProductVersion) Thocircng tin Company vagrave Product được thiết lập thocircng qua đặc tiacutenh AssemblyCompany vagrave AssemblyProduct (thường nằm trong file AssemblyInfovb) ConsoleWriteLine(Company amp _ SystemWindowsFormsApplicationCompanyName) ConsoleWriteLine(Product amp _ SystemWindowsFormsApplicationProductName) Thocircng tin bản địa lagrave bản địa hiện hagravenh (trong trường hợp nagravey lagrave 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 nagravey lagrave khocircng coacute) ConsoleWriteLine(Culture amp _ SystemWindowsFormsApplicationCurrentCultureToString()) ConsoleWriteLine(Culture Code amp _ SystemWindowsFormsApplicationCurrentCultureDisplayName) ConsoleReadLine() End SubEnd ModuleChuacute yacute rằng GetExecutingAssembly luocircn trả về một tham chiếu đến assembly magrave matilde lệnh đang thực thi ở đoacute Noacutei caacutech khaacutec nếu bạn chạy một ứng dụng Windows (assembly A) coacute sử dụng một thagravenh phần độc lập (assembly B) vagrave thagravenh phần đoacute cho gọi GetExecutingAssembly noacute sẽ nhận được một tham chiếu đến assembly B Bạn cũng coacute thể sử dụng GetCallingAssembly (thu lấy assembly magrave lệnh gọi được định vị ở đoacute) hoặc GetEntryAssembly (trả về assembly coacute thể thực thi đối với miền ứng dụng hiện hagravenh) Assembly lagrave một từ khoacutea dagravenh riecircng trong Microsoft Visualcong Basic NET Do đoacute nếu muốn tham chiếu kiểu SystemReflectionAssembly 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 vuocircng Lệnh nagravey lagravem việcDim Asm As SystemReflectionAssembly

Lệnh nagravey cũng lagravem việc giả sử bạn đatilde nhập khocircng gian tecircn SystemReflectionDim Asm As [Assembly]

Lệnh nagravey sinh ra lỗi biecircn dịch vigrave Assembly lagrave từ khoacutea dagravenh riecircngDim Asm As Assembly

Tạo form với hiệu ứng DropShadowrất đơn giảnbạn chỉ cần khai baacuteo tham số CS_DROPSHADOW vagrave với noacute bạn coacute thể lagravem cho bất cứ Window nagraveo cũng sẽ coacute một caacutei boacuteng như dưới đacircy bằng trao cho lớp của noacute tham số trecircn

[vb]Protected Overrides ReadOnly Property CreateParams() As SystemWindowsFormsCreateParams Get Dim parameters As CreateParams = MyBaseCreateParams parametersClassStyle = parametersClassStyle 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 lagravem gigrave đoacute) vagrave thời điểm kết thuacutec 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 = DateTimeNow() timeDifference = timeEndSubtract(timeStart) timeElapsed = timeElapsedAdd(timeDifference) Return timeElapsedToString()

End Function

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

Implementation

Dim timeStart As DateTime

timeStart = DateTimeNow()

caacutec cacircu lệnh lagravem chuyện gigrave đoacute

MelblDurationText = GetDuration(timeStart)

vagrave lấy kiểu ngagravey khocircng coacute gắn giờDim _date As Date = DateTimeNowDate

SubClass trong NET Triacutenh ldquohellipWindows gửi thocircng điệp lagrave một hằng số tới caacutec form vagrave caacutec control của VB để baacuteo cho chuacuteng biết vị triacute chuột ở đacircu khi nagraveo thigrave cần vẽ lại phiacutem nagraveo đang được nhấn vagrave nhiều thocircng điệp khaacutec Kỹ thuật subclassing lagrave để xử lyacute chặn những thocircng điệp nagravey trước khi chuacuteng đến được caacutec form vagrave control Bằng caacutech chặn caacutec thocircng điệp nagravey vagrave xử lyacute vagravei thứ trước khi chuacuteng đến điacutech chuacuteng ta coacute thể coacute caacutec tiacutenh năng riecircng (như tự vẽ lại caacutec control theo yacute riecircng)Subclassing lagrave một kỹ thuật tinh vi chỉ cần một lỗi nhỏ (viacute dụ như do bạn giải phoacuteng tagravei nguyecircn khocircng tốt dẫn đến việc thất thoaacutet tagravei nguyecircn của hệ thống) lagrave coacute thể dẫn đến việc hệ thống của bạn bị thiếu tagravei nguyecircn lagravem cho hệ thống hoạt động khocircng cograven tốt nữa (chậm đi) nặng hơn lagrave VB bị shut down thậm chiacute treo maacutey Tuy nhiecircn noacutei điều nagravey lagrave để bạn yacute thức được vấn đề chứ bạn cũng khocircng necircn quaacute lo ngại về noacute Vagrave thecircm 1 chuacute yacute lagrave bạn cũng khocircng necircn bấm nuacutet stop của VB khi chương trigravenh đang chạy magrave bạn necircn đoacuteng form 1 caacutech thocircng thường (bấm nuacutet close) để thực hiện tốt việc giải phoacuteng tagravei nguyecircnhelliprdquo Trong VB6 bạn coacute thể dugraveng Kỹ thuật nagravey bằng caacutech tạo ra một Lớp vagrave dugraveng caacutec hagravem API như SetWindowLongCallWindowProchay Sendmessage vagrave một số tin nhắn Cograven trong NET bạn coacute thể bắt tin nhắn vagrave xứ liacute chuacuteng bằng caacutech dugraveng phương thức WndProc trong Form như sau [vb]Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage)

Select Case mMsg Case WM_MOUSEMOVE xử liacute tin nhắn ở đacircy End Select End Sub[vb] Nhưng caacutech dugraveng trecircn coacute một vagravei nhược điểm như một số Control khocircng coacute phương thức nagravey vagrave giống như liacute do magrave trong VB6 bạn phải tạo một lớp riecircng để SubClassVigrave vậy việc SubClass trong NET sẽ dễ dagraveng hơn khi dugraveng Lớp NativeWindowBạn coacute thể tạo bằng caacutech tạo một lớp mới vagrave thừa hưởng lại từ Lớp NativeWindow

[vb]Imports SystemRuntimeInteropServices Imports SystemDrawing Imports SystemDrawingDrawing2D

Public Class Class1 Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage) Select Case mMsg Case WM_NCACTIVATE Sứ liacute tin nhắn ở đacircy End Select MyBaseWndProc(m) End Sub End Class[vb] Caacutech dugraveng lớp nagravey như sau Trong NativeWindow coacute 3 phương thức magrave bạn dugraveng để bắt đầu với kỹ thuật SubClass trong NET 1 AssignHandle( handle as IntPtr) Gaacuten một đối tượng vagraveo handle của cửa sổ vagrave bắt đầu Subclass 2 ReleaseHandle( handle as IntPtr) Huỷ bỏ Subclass vagrave đưa giaacute trị của handle về giagrave trị 0 [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseLoad sAssignHandle(MeHandle) End Sub

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

dụng tham chiếu dạng đầy đủ hoặc bạn phải đặt từ Assembly trong dấu ngoặc vuocircng Lệnh nagravey lagravem việcDim Asm As SystemReflectionAssembly

Lệnh nagravey cũng lagravem việc giả sử bạn đatilde nhập khocircng gian tecircn SystemReflectionDim Asm As [Assembly]

Lệnh nagravey sinh ra lỗi biecircn dịch vigrave Assembly lagrave từ khoacutea dagravenh riecircngDim Asm As Assembly

Tạo form với hiệu ứng DropShadowrất đơn giảnbạn chỉ cần khai baacuteo tham số CS_DROPSHADOW vagrave với noacute bạn coacute thể lagravem cho bất cứ Window nagraveo cũng sẽ coacute một caacutei boacuteng như dưới đacircy bằng trao cho lớp của noacute tham số trecircn

[vb]Protected Overrides ReadOnly Property CreateParams() As SystemWindowsFormsCreateParams Get Dim parameters As CreateParams = MyBaseCreateParams parametersClassStyle = parametersClassStyle 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 lagravem gigrave đoacute) vagrave thời điểm kết thuacutec 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 = DateTimeNow() timeDifference = timeEndSubtract(timeStart) timeElapsed = timeElapsedAdd(timeDifference) Return timeElapsedToString()

End Function

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

Implementation

Dim timeStart As DateTime

timeStart = DateTimeNow()

caacutec cacircu lệnh lagravem chuyện gigrave đoacute

MelblDurationText = GetDuration(timeStart)

vagrave lấy kiểu ngagravey khocircng coacute gắn giờDim _date As Date = DateTimeNowDate

SubClass trong NET Triacutenh ldquohellipWindows gửi thocircng điệp lagrave một hằng số tới caacutec form vagrave caacutec control của VB để baacuteo cho chuacuteng biết vị triacute chuột ở đacircu khi nagraveo thigrave cần vẽ lại phiacutem nagraveo đang được nhấn vagrave nhiều thocircng điệp khaacutec Kỹ thuật subclassing lagrave để xử lyacute chặn những thocircng điệp nagravey trước khi chuacuteng đến được caacutec form vagrave control Bằng caacutech chặn caacutec thocircng điệp nagravey vagrave xử lyacute vagravei thứ trước khi chuacuteng đến điacutech chuacuteng ta coacute thể coacute caacutec tiacutenh năng riecircng (như tự vẽ lại caacutec control theo yacute riecircng)Subclassing lagrave một kỹ thuật tinh vi chỉ cần một lỗi nhỏ (viacute dụ như do bạn giải phoacuteng tagravei nguyecircn khocircng tốt dẫn đến việc thất thoaacutet tagravei nguyecircn của hệ thống) lagrave coacute thể dẫn đến việc hệ thống của bạn bị thiếu tagravei nguyecircn lagravem cho hệ thống hoạt động khocircng cograven tốt nữa (chậm đi) nặng hơn lagrave VB bị shut down thậm chiacute treo maacutey Tuy nhiecircn noacutei điều nagravey lagrave để bạn yacute thức được vấn đề chứ bạn cũng khocircng necircn quaacute lo ngại về noacute Vagrave thecircm 1 chuacute yacute lagrave bạn cũng khocircng necircn bấm nuacutet stop của VB khi chương trigravenh đang chạy magrave bạn necircn đoacuteng form 1 caacutech thocircng thường (bấm nuacutet close) để thực hiện tốt việc giải phoacuteng tagravei nguyecircnhelliprdquo Trong VB6 bạn coacute thể dugraveng Kỹ thuật nagravey bằng caacutech tạo ra một Lớp vagrave dugraveng caacutec hagravem API như SetWindowLongCallWindowProchay Sendmessage vagrave một số tin nhắn Cograven trong NET bạn coacute thể bắt tin nhắn vagrave xứ liacute chuacuteng bằng caacutech dugraveng phương thức WndProc trong Form như sau [vb]Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage)

Select Case mMsg Case WM_MOUSEMOVE xử liacute tin nhắn ở đacircy End Select End Sub[vb] Nhưng caacutech dugraveng trecircn coacute một vagravei nhược điểm như một số Control khocircng coacute phương thức nagravey vagrave giống như liacute do magrave trong VB6 bạn phải tạo một lớp riecircng để SubClassVigrave vậy việc SubClass trong NET sẽ dễ dagraveng hơn khi dugraveng Lớp NativeWindowBạn coacute thể tạo bằng caacutech tạo một lớp mới vagrave thừa hưởng lại từ Lớp NativeWindow

[vb]Imports SystemRuntimeInteropServices Imports SystemDrawing Imports SystemDrawingDrawing2D

Public Class Class1 Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage) Select Case mMsg Case WM_NCACTIVATE Sứ liacute tin nhắn ở đacircy End Select MyBaseWndProc(m) End Sub End Class[vb] Caacutech dugraveng lớp nagravey như sau Trong NativeWindow coacute 3 phương thức magrave bạn dugraveng để bắt đầu với kỹ thuật SubClass trong NET 1 AssignHandle( handle as IntPtr) Gaacuten một đối tượng vagraveo handle của cửa sổ vagrave bắt đầu Subclass 2 ReleaseHandle( handle as IntPtr) Huỷ bỏ Subclass vagrave đưa giaacute trị của handle về giagrave trị 0 [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseLoad sAssignHandle(MeHandle) End Sub

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

End Function

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

Implementation

Dim timeStart As DateTime

timeStart = DateTimeNow()

caacutec cacircu lệnh lagravem chuyện gigrave đoacute

MelblDurationText = GetDuration(timeStart)

vagrave lấy kiểu ngagravey khocircng coacute gắn giờDim _date As Date = DateTimeNowDate

SubClass trong NET Triacutenh ldquohellipWindows gửi thocircng điệp lagrave một hằng số tới caacutec form vagrave caacutec control của VB để baacuteo cho chuacuteng biết vị triacute chuột ở đacircu khi nagraveo thigrave cần vẽ lại phiacutem nagraveo đang được nhấn vagrave nhiều thocircng điệp khaacutec Kỹ thuật subclassing lagrave để xử lyacute chặn những thocircng điệp nagravey trước khi chuacuteng đến được caacutec form vagrave control Bằng caacutech chặn caacutec thocircng điệp nagravey vagrave xử lyacute vagravei thứ trước khi chuacuteng đến điacutech chuacuteng ta coacute thể coacute caacutec tiacutenh năng riecircng (như tự vẽ lại caacutec control theo yacute riecircng)Subclassing lagrave một kỹ thuật tinh vi chỉ cần một lỗi nhỏ (viacute dụ như do bạn giải phoacuteng tagravei nguyecircn khocircng tốt dẫn đến việc thất thoaacutet tagravei nguyecircn của hệ thống) lagrave coacute thể dẫn đến việc hệ thống của bạn bị thiếu tagravei nguyecircn lagravem cho hệ thống hoạt động khocircng cograven tốt nữa (chậm đi) nặng hơn lagrave VB bị shut down thậm chiacute treo maacutey Tuy nhiecircn noacutei điều nagravey lagrave để bạn yacute thức được vấn đề chứ bạn cũng khocircng necircn quaacute lo ngại về noacute Vagrave thecircm 1 chuacute yacute lagrave bạn cũng khocircng necircn bấm nuacutet stop của VB khi chương trigravenh đang chạy magrave bạn necircn đoacuteng form 1 caacutech thocircng thường (bấm nuacutet close) để thực hiện tốt việc giải phoacuteng tagravei nguyecircnhelliprdquo Trong VB6 bạn coacute thể dugraveng Kỹ thuật nagravey bằng caacutech tạo ra một Lớp vagrave dugraveng caacutec hagravem API như SetWindowLongCallWindowProchay Sendmessage vagrave một số tin nhắn Cograven trong NET bạn coacute thể bắt tin nhắn vagrave xứ liacute chuacuteng bằng caacutech dugraveng phương thức WndProc trong Form như sau [vb]Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage)

Select Case mMsg Case WM_MOUSEMOVE xử liacute tin nhắn ở đacircy End Select End Sub[vb] Nhưng caacutech dugraveng trecircn coacute một vagravei nhược điểm như một số Control khocircng coacute phương thức nagravey vagrave giống như liacute do magrave trong VB6 bạn phải tạo một lớp riecircng để SubClassVigrave vậy việc SubClass trong NET sẽ dễ dagraveng hơn khi dugraveng Lớp NativeWindowBạn coacute thể tạo bằng caacutech tạo một lớp mới vagrave thừa hưởng lại từ Lớp NativeWindow

[vb]Imports SystemRuntimeInteropServices Imports SystemDrawing Imports SystemDrawingDrawing2D

Public Class Class1 Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage) Select Case mMsg Case WM_NCACTIVATE Sứ liacute tin nhắn ở đacircy End Select MyBaseWndProc(m) End Sub End Class[vb] Caacutech dugraveng lớp nagravey như sau Trong NativeWindow coacute 3 phương thức magrave bạn dugraveng để bắt đầu với kỹ thuật SubClass trong NET 1 AssignHandle( handle as IntPtr) Gaacuten một đối tượng vagraveo handle của cửa sổ vagrave bắt đầu Subclass 2 ReleaseHandle( handle as IntPtr) Huỷ bỏ Subclass vagrave đưa giaacute trị của handle về giagrave trị 0 [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseLoad sAssignHandle(MeHandle) End Sub

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Select Case mMsg Case WM_MOUSEMOVE xử liacute tin nhắn ở đacircy End Select End Sub[vb] Nhưng caacutech dugraveng trecircn coacute một vagravei nhược điểm như một số Control khocircng coacute phương thức nagravey vagrave giống như liacute do magrave trong VB6 bạn phải tạo một lớp riecircng để SubClassVigrave vậy việc SubClass trong NET sẽ dễ dagraveng hơn khi dugraveng Lớp NativeWindowBạn coacute thể tạo bằng caacutech tạo một lớp mới vagrave thừa hưởng lại từ Lớp NativeWindow

[vb]Imports SystemRuntimeInteropServices Imports SystemDrawing Imports SystemDrawingDrawing2D

Public Class Class1 Inherits NativeWindow

Protected Overrides Sub WndProc(ByRef m As SystemWindowsFormsMessage) Select Case mMsg Case WM_NCACTIVATE Sứ liacute tin nhắn ở đacircy End Select MyBaseWndProc(m) End Sub End Class[vb] Caacutech dugraveng lớp nagravey như sau Trong NativeWindow coacute 3 phương thức magrave bạn dugraveng để bắt đầu với kỹ thuật SubClass trong NET 1 AssignHandle( handle as IntPtr) Gaacuten một đối tượng vagraveo handle của cửa sổ vagrave bắt đầu Subclass 2 ReleaseHandle( handle as IntPtr) Huỷ bỏ Subclass vagrave đưa giaacute trị của handle về giagrave trị 0 [vb] Private s As New Class1 Private Sub Form1_Load(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseLoad sAssignHandle(MeHandle) End Sub

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Private Sub Form1_Closed(ByVal sender As Object ByVal e As SystemEventArgs) Handles MyBaseClosed sReleaseHandle() End Sub[vb] Ok

C aacutech truy vần dữ liệu trực tiếp trong dataset Về lớp khocircng kết nối Dataset Migravenh muốn hỏi caacutec bạn lagrave coacute caacutech nagraveo để truy vấn trực tiếp thocircng tin trong dataset khocircng Viacute dụ migravenh coacute một bảng tecircn lagrave Mathang với 3 cột MaHangTenHangGiaBan Trong chương trigravenh của migravenh khi user thay đổi matilde hagraveng thigrave migravenh sẽ tigravem caacutec thocircng tin cograven lại bằng cacircu lệnh SQL sau Select from MatHang Where Mahang like mahang thigrave tất nhiecircn noacute sẽ cho ra kết quả Nhưng nếu vậy thigrave mỗi lần đổi matilde hagraveng lagrave mỗi lần connect đến server sau đoacute select dữ liệu rồi trả về biến dataset rồi lại đưa vagraveo datagrid Như vậy sẽ rất lacircu vagrave khocircng tối ưu Yacute tưởng của migravenh lagrave trước khi vagraveo Form thigrave migravenh sẽ Select hết thocircng tin trong bảng Mathang lưu vagraveo biến toagraven cục dataset Sau đoacute chương trigravenh sẽ chỉ select trecircn dataset nagravey magrave thocirci vagrave khocircng cần kết nối lại server nữa như vậy sẽ rất lagrave nhanh caacutec bạn coacute đồn yacute với migravenh khocircng Nhưng vấn đề lagrave lagravem sao coacute thể lagravem cho dataset hiểu được cacircu lệnh SQL magrave trả về thocircng tin minh cần vagrave đưa vagraveo datagrid sau đoacute show cho user xem

Về vấn đề nagravey bạn coacute thể dugraveng một mảng datarow để lọc những dograveng thỏa điều kiện bạn lagravem như vầy Dim dr as datarow() dr=dsTables(Mathang)Select(Mahang like amp mahang amp )

Caacutech cagravei đặt 1 ứng dụng VB2005NET trecircn mạng LAN như thế nagraveoTocirci coacute 1 ứng dụng viết bằng VBNET Khi chạy ứng dụng trecircn maacutey cagravei đặt chương trigravenh thigrave noacute hoạt động bigravenh thường Tocirci coacute tạo một shortcut đến chương trigravenh từ một maacutey tiacutenh khaacutec trong mạng LAN vagrave chạy chương trigravenh từ shortcut nagravey thigrave xuất hiện thocircng baacuteo lỗi như sau

Application attempted to perform an operation not allowed by theSecurity policy To grant this application the required permission contactYour system administrator or use the Microsoft NET Framework

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Configuration 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 typelsquoSystemDataOleDbOleDbPermission SystemData Version=2000Culture=neutral PulicKeyToken=b77a5c561934e089rsquo failed

Tocirci biết rằng lỗi trecircn lagrave do chương trigravenh coacute sử dụng cơ sở dữ liệu Access vagrave khocircng biết caacutech khaacutec phục như thế nagraveo Nhờ caacutec chuyecircn gia về VBNET hướng dẫn tocirci cagravei đặt chương trigravenh như thế nagraveo để mọi maacutey trong mạng LAN đều coacute thể sử dụng chung chương trigravenh được cagravei trecircn 1 maacuteyCấu higravenh mặc định của net framwork khocircng cho pheacutep chạy caacutec net APP trecircn network vigrave noacute được cho lagrave untrust muốn caacutec net APP triển khai được trecircn caacutec untrust location như maped network cần lagravem theo bước sau Vagraveo settings - Control Panel Administrative tools Microsoft NET Framework Configuration nhắp phải vagraveo Runtime Security Policy chọn Adjust Security rugravei nhấn next chỉnh Local Intranet sang Full Trust rugravei NEXT Vậy lagrave ok

Dynamic Menu Class coding

Option ExplicitPrivate Declare Function GetLastError Lib kernel32dll () As Long Exposed EnumerationPublic Enum mceItemStates mceDisabled = 1 mceGrayed = 2End Enum

Property variablesPrivate psCaption As String Caption of menu item (with the arrow gt) 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 = ampH0ampPrivate Const MF_BYPOSITION = ampH400Private Const MF_CHECKED = ampH8ampPrivate Const MF_DISABLED = ampH2ampPrivate Const MF_GRAYED = ampH1ampPrivate Const MF_MENUBARBREAK = ampH20ampPrivate Const MF_MENUBREAK = ampH40amp

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Private Const MF_POPUP = ampH10ampPrivate Const MF_SEPARATOR = ampH800ampPrivate Const MF_STRING = ampH0ampPrivate Const MIIM_ID = ampH2Private Const MIIM_SUBMENU = ampH4Private Const MIIM_TYPE = ampH10Private Const TPM_LEFTALIGN = ampH0ampPrivate Const TPM_RETURNCMD = ampH100ampPrivate Const TPM_RIGHTBUTTON = ampH2

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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 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 its 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) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Default item If bDefault Then SetMenuDefaultItem piHwnd iMenuID 0 Disabled (Regular color text) 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 oSubmenuHwnd ByVal oSubmenuCaption 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 Cant 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 ltgt -1 Then Dim rt As RECT GetWindowRect iControlHwnd rt iX = rtLeft iY = rtBottom Else Dim pt As POINT GetCursorPos pt If X = -1 Then iX = ptX Else iX = X

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

If Y = -1 Then iY = ptY Else iY = Y End If Show = TrackPopupMenuEx(piHwnd TPM_RETURNCMD Or TPM_RIGHTBUTTON iX iY iHwnd ByVal 0amp) End Function

Dynamic Menu Form coding

Option Explicit

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

lblLabelBackColor = vbButtonFace lblLabelForeColor = vbWindowText End Sub

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

lblLabelBackColor = vbHighlight lblLabelForeColor = 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 dont have a handle set xy manually x1 = (MeLeft + 45 + lblLabelLeft) 15 15 twips per pixel y1 = (MeTop + 525 + lblLabelHeight) 15 Add a few of the main menu items oMenuAdd 1 Item 1 oMenuAdd 2 Item 2 True imglstImagesListImages(1)Picture oMenuAdd 3 Item 3 mceGrayed oMenuAdd 4 - Seperator Build our submenus when needed oSubmenu1Caption = Submenu 1 oSubmenu1Add 20 Submenu 1 Item 1 mceGrayed imglstImagesListImages(2)Picture oSubmenu1Add 21 Submenu 1 Item 2 imglstImagesListImages(3)Picture oSubmenu1Add 22 Submenu 1 Item 3 imglstImagesListImages(4)Picture Submenu of the first submenu oSubmenu2Caption = Submenu 2 oSubmenu2Add 30 Submenu 2 Item 1 oSubmenu2Add 31 Submenu 2 Item 2

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

oSubmenu2Add 32 Submenu 2 Item 3 Add second submenu to first oSubmenu1Add 33 oSubmenu2 Add first submenu to main oMenuAdd 5 oSubmenu1 oMenuAdd 6 - Another seperator Build third submenu oSubmenu3Caption = Submenu 3 oSubmenu3Add 40 Submenu 2 Item 1 imglstImagesListImages(2)Picture oSubmenu3Add 41 Submenu 3 Item 2 imglstImagesListImages(3)Picture oSubmenu3Add 42 Submenu 3 Item 3 imglstImagesListImages(4)Picture oMenuAdd 7 oSubmenu3 oMenuAdd 8 - Yet another The remaining items in the main menu oMenuAdd 9 Item 4 True oMenuAdd 10 Item 5 imglstImagesListImages(4)Picture oMenuAdd 11 Item 6 True mceGrayed Show popup Ret = oMenuShow(MeHwnd x1 y1) Release objects Set oSubmenu1 = Nothing Set oSubmenu2 = Nothing Set oSubmenu3 = Nothing Set oMenu = Nothing MsgBox You chose menu ID amp 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 DebugWriteLine(Boot Mode amp BootMode) DebugWriteLine(Computer Name amp ComputerName) DebugWriteLine(Double Byte Character Set Enabled _ amp DBCSEnabled) DebugWriteLine(Network Connection Present amp isConnectedToNetwork)

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

DebugWriteLine(Menu Font Name amp MenuFontName) DebugWriteLine(Menu Font Name amp MenuFontSize) DebugWriteLine(Menu Height amp MenuHeight) DebugWriteLine(Hebrew and Arabic supported amp MidEastEnabled) DebugWriteLine( of attached monitors amp MonitorCount) DebugWriteLine(Is mouse present amp MousePresent) DebugWriteLine(Is mouse wheel present amp MouseWheelPresent) DebugWriteLine( of mouse buttons amp MouseButtons) DebugWriteLine(Is Pen Windows Supported amp PenWindows) DebugWriteLine(Primary Monitor Size amp PrimaryMonitorSize) DebugWriteLine(Is OS Security Present amp Secure) DebugWriteLine(Domain Name amp UserDomainName) DebugWriteLine(User Name amp UserName) DebugWriteLine(Current process running in user interactive mode amp UserInteractive) DebugWriteLine(Working Area amp 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 SystemInformationBootModeToString

End Function Public Function ComputerName() As String the computername Return SystemInformationComputerName

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

End Function Public Function MenuFontName() As String operating system font name for menus Return SystemInformationMenuFontFontFamilyName

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

End Function Public Function MenuFontSize() As Integer operating system font name for menus Return SystemInformationMenuFontSize

End Function Public Function MenuHeight() As Integer height of one menu line in pixel Return SystemInformationMenuHeight

End Function

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

Public Function MouseButtons() As Integer How many mouse buttons Return SystemInformationMouseButtons End Function

Public Function MousePresent() As Boolean is mouse present Return SystemInformationMousePresent End Function Public Function MouseWheelPresent() As Boolean is mouse with mouse wheel present Return SystemInformationMouseWheelPresent End Function Public Function isConnectedToNetwork() As Boolean connection to network present Return SystemInformationNetwork End Function Public Function PenWindows() As Boolean

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Are Microsoft Windows for Pen Computing extensions installed Return SystemInformationPenWindows

End Function Public Function PrimaryMonitorSize() As String Size of primary monitor Return SystemInformationPrimaryMonitorSizeToString

End Function Public Function Secure() As Boolean is security present on operating system Return SystemInformationSecure

End Function Public Function UserDomainName() As String the domain name for the current user Return SystemInformationUserDomainName End Function Public Function UserInteractive() As Boolean is current process running in user-interactive mode Return SystemInformationUserInteractive End Function Public Function UserName() As String user name Return SystemInformationUserName End Function Public Function WorkingArea() As String Return SystemInformationWorkingAreaToString

End FunctionEnd Class

SQL Data Provider VBNET 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 SystemIO

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Imports SystemTextImports SystemDataImports SystemDataSqlClient

Namespace SqlDataProvider

ltsummarygt This class provides a fast and universal method for accessing SQL Server databaseThis class cannot be inherited ltsummarygt Public NotInheritable Class SqlDatabase

Region Local Property Declarations

Dim _connectionString As String

End Region

Region Constructor

ltsummarygt Initializes a new instance of the ADOSqlDatabase class ltsummarygt ltparam name=connectionStringgtThe connection used to open the SQL Server databaseltparamgt Public Sub New(ByVal connectionString As String) _connectionString = connectionString End Sub

End Region

Region Public Properties

ltsummarygt Gets or sets the string used to open a SQL Server database ltsummarygt ltreturnsgtThe connection string that includes the source database name and other parameters needed to establish the initial connectionltreturnsgt 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 cmdParametersAdd(p) Next End Sub

Private Sub AssignParameters(ByVal cmd As SqlCommand ByVal parameterValues() As Object) If Not (cmdParametersCount - 1 = parameterValuesLength) Then Throw New ApplicationException(Stored procedures parameters and parameter values does not match) Dim i As Integer For Each param As SqlParameter In cmdParameters If Not (paramDirection = ParameterDirectionOutput) AndAlso Not (paramDirection = ParameterDirectionReturnValue) Then paramValue = parameterValues(i) i += 1 End If Next

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

End Sub

End Region

Region ExecuteNonQuery

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteNonQuery() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt Executes a Transact-SQL statement against the connection and returns the number of rows affected ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe number of rows affectedltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction()

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

commandTransaction = transaction res = commandExecuteNonQuery() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteScalar

ltsummarygt 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 ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

ltsummarygt 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 ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtThe first column of the first row in the result set or a null reference if the result set is emptyltreturnsgt 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) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) transaction = connectionBeginTransaction() commandTransaction = transaction res = commandExecuteScalar() returnValue = commandParameters(0)Value transactionCommit() Catch ex As Exception If Not (transaction Is Nothing) Then transactionRollback() End If Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If Not (command Is Nothing) Then commandDispose() If Not (transaction Is Nothing) Then transactionDispose() End Try Return res End Function

End Region

Region ExecuteReader

ltsummarygt Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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) commandCommandType = cmdType MeAssignParameters(command parameters) connectionOpen() res = commandExecuteReader(CommandBehaviorCloseConnection) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

ltsummarygt

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Sends the SystemDataSqlClientSqlCommandCommandText to the SystemDataSqlClientSqlCommandConnection and builds a SystemDataSqlClientSqlDataReader using one of the SystemDataCommandBehavior values ltsummarygt ltparam name=spnamegtThe stored procedure to execute at the data sourceltparamgt ltparam name=returnValuegtThe returned value from stored procedureltparamgt ltparam name=parameterValuesgtThe parameter values of the stored procedureltparamgt ltreturnsgtA SystemDataSqlClientSqlDataReader objectltreturnsgt 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 Try connection = New SqlConnection(ConnectionString) command = New SqlCommand(spname connection) commandCommandType = CommandTypeStoredProcedure connectionOpen() SqlCommandBuilderDeriveParameters(command) MeAssignParameters(command parameterValues) res = commandExecuteReader(CommandBehaviorCloseConnection) returnValue = commandParameters(0)Value Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) End Try Return CType(res IDataReader) End Function

End Region

Region FillDataset

ltsummarygt Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table ltsummarygt ltparam name=cmdgtThe Transact-SQL statement or stored procedure to execute at the data sourceltparamgt ltparam name=cmdTypegtA value indicating how the SystemDataSqlClientSqlCommandCommandText property is to be interpretedltparamgt ltparam name=parametersgtThe parameters of the Transact-SQL statement or stored procedureltparamgt ltreturnsgtA SystemDataDataset objectltreturnsgt 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) commandCommandType = cmdType AssignParameters(command parameters) sqlda = New SqlDataAdapter(command) sqldaFill(res) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (command Is Nothing) Then commandDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Region ExecuteDataset

ltsummarygt Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name ltsummarygt ltparam name=insertCmdgtA command used to insert new records into the data sourceltparamgt ltparam name=updateCmdgtA command used to update records in the data sourceltparamgt ltparam name=deleteCmdgtA command for deleting records from the data setltparamgt ltparam name=dsgtThe SystemDataDataSet to use to update the data source ltparamgt ltparam name=srcTablegtThe name of the source table to use for table mappingltparamgt ltreturnsgtThe number of rows successfully updated from the SystemDataDataSetltreturnsgt 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 insertCmdConnection = connection sqldaInsertCommand = insertCmd If Not (updateCmd Is Nothing) Then updateCmdConnection = connection sqldaUpdateCommand = updateCmd If Not (deleteCmd Is Nothing) Then deleteCmdConnection = connection sqldaDeleteCommand = deleteCmd res = sqldaUpdate(ds srcTable) Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If Not (connection Is Nothing) Then connectionDispose() If Not (insertCmd Is Nothing) Then insertCmdDispose() If Not (updateCmd Is Nothing) Then updateCmdDispose() If Not (deleteCmd Is Nothing) Then deleteCmdDispose() If Not (sqlda Is Nothing) Then sqldaDispose() End Try Return res End Function

End Region

Region ExecuteScript

ltsummarygt Executes a SQL query file against the connection ltsummarygt ltparam name=filenamegtSQL query file nameltparamgt ltparam name=parametersgtThe parameters of the SQL query fileltparamgt 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 FileModeOpen FileAccessRead) sReader = New StreamReader(fStream) connection = New SqlConnection(ConnectionString) command = connectionCreateCommand() connectionOpen() While (Not sReaderEndOfStream) Dim sb As New StringBuilder While (Not sReaderEndOfStream)

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Dim s As String = sReaderReadLine If (Not StringIsNullOrEmpty(s)) AndAlso (sToUpperTrim = GO) Then Exit While End If sbAppendLine(s) End While commandCommandText = sbToString commandCommandType = CommandTypeText AssignParameters(command parameters) commandExecuteNonQuery() End While Catch ex As Exception Throw New SqlDatabaseException(exMessage exInnerException) Finally If (Not IsNothing(connection)) AndAlso (connectionState = ConnectionStateOpen) Then connectionClose() If (Not IsNothing(command)) Then commandDispose() If (Not IsNothing(sReader)) Then sReaderClose() If (Not IsNothing(fStream)) Then fStreamClose() 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 ConnectionStringscom

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 SqlDbTypeNVarChar 120)params(0)Value = Stefanparams(1) = New SqlParameter(Lastname SqlDbTypeNVarChar 120)params(1)Value = CameronsqldbExecuteNonQuery(Insert Into dboUsers(Firstname LastName) Values(FirstName LastName) CommandTypeText params)

If you are using stored procedureyou can execute that without declaring parameters such as following code

sqldbExecuteNonQuery(dboCreateUser 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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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 = sqldbExecuteScalar(Select Count() From dboUsers CommandTypeText) MsgBox(Number of row(s) amp count)

ExecuteReader Method

Sends the CommandText to the Connection and builds a SqlDataReader

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim params(0) As SqlParameter params(0) = New SqlParameter(Id SqlDbTypeInt) params(0)Value = 1

Dim dr As IDataReader = sqldbExecuteReader(Select From dboUsers Where (Id = Id) CommandTypeText params) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

There is a sample for using stored procedure

Create Procedure [dbo][GetUserInfo] ( Id int ) As Begin Select From dboUsers Where (Id = Id) End

Dim FirstName As String = StringEmpty Dim LastName As String = StringEmpty

Dim dr As IDataReader = sqldbExecuteReader(dboGetUserInfo Nothing 1) While drRead() FirstName = dr(Firstname) LastName = dr(Lastname) End While drClose()

MsgBox(FirstName amp amp LastName MsgBoxStyleInformation)

Using Return Value Parameter

If you are using stored procedureyou can get the value of return value parameter

Create Procedure dboUserExists ( Firstname nvarchar(120)

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Lastname nvarchar(120) )AsBegin If Exists(Select From dboUsers Where (Firstname = Firstname) And (Lastname = Lastname)) Return 1End

Dim retval As IntegersqldbExecuteNonQuery(dboUserExists retval Stefan Cameron)MsgBox(User Exists amp IIf(retval = 1 Yes No))

FillDataset Method

Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table

Binding a DataGridView with FillDataset method

DataGridView1DataSource = sqldbFillDataset(Select From dboUsers CommandTypeText)Tables(0)

ExecuteDataset Method

Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Getting the SystemDataDataSetDim ds As DataSet = CType(DataGridView1DataSource DataTable)DataSet

Declaring insert command objectDim inscmd As New SqlCommand(Insert Into dboUsers(Firstname Lastname) Values(Firstname Lastname))With inscmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring update command objectDim updcmd As New SqlCommand(Update dboUsers Set Firstname = Firstname Lastname = Lastname Where (Id = Id))With updcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = Id ParametersAdd(New SqlParameter(Firstname SqlDbTypeNVarChar 120))SourceColumn = Firstname ParametersAdd(New SqlParameter(Lastname SqlDbTypeNVarChar 120))SourceColumn = LastnameEnd With

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Declaring delete command objectDim delcmd As New SqlCommand(Delete From dboUsers Where (Id = Id))With delcmd CommandType = CommandTypeText ParametersAdd(New SqlParameter(Id SqlDbTypeInt))SourceColumn = IdEnd With

Updating data sourcesqldbExecuteDataset(inscmd updcmd delcmd ds dsTables(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 youve defined your own KeyDown Events in Private Sub Form_KeyDown(KeyCode As Integer Shift As Integer) you wouldnt want to use VBs Menu Editor 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 voilaExample using a MenuItem and a MsgBoxThe MenuItem is Named mnuFileOpenThe MenuItems Caption property will get put into theForms Load Event

Private Sub Form_Load()mnuFileOpenCaption = Open amp Chr$(vbKeyTab) amp Ctrl+OEnd 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 FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Define the mnuFileOpen_Click() eventPrivate Sub mnuFileOpen_Click()Actions to perform when the FileOpen MenuItemis ClickedExampleMsgBox Here is a Message Box using the Tab Character amp vbCrLf amp Chr$(vbKeyTab) amp Whats up DocEnd Sub

Opening a Form by Type or Namehttpvbcitycomforumsfaqasptid=33930

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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 controlobject)

The answer is you dont 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 cant 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 its always the same form thats 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 dont 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 youll 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(ActivatorCreateInstance(GetType(Form1)) Form)Show()Or for better readability the same code split upCode

Dim FormToOpen As Type FormToOpen = GetType(Form1) Dim frm As Form = CType(ActivatorCreateInstance(FormToOpen) Form) frmShow()

Looking back VB6 In vb6 we could add a form with

Code VB6 Dim FormName as String

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

How To Print a Formhttpvbcitycomforumsfaqasptid=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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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 GDI32DLL ( _ 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 SystemObject ByVal e As SystemEventArgs) Handles btnPrintClick

We make the form look pretty before its picture ApplicationDoEvents() MeRefresh() ApplicationDoEvents() Get a Graphics Object from the form Dim FormG As Graphics = MeCreateGraphics Create a bitmap from that graphics Dim i As New Bitmap(MeWidth MeHeight FormG) Create a Graphics object in memory from that bitmap Dim memG As Graphics = GraphicsFromImage(i) get the IntPtrs of the graphics Dim HDC1 As IntPtr = FormGGetHdc Dim HDC2 As IntPtr = memGGetHdc get the picture BitBlt(HDC2 0 0 MeClientRectangleWidth MeClientRectangleHeight HDC1 0 0 13369376) Clone the bitmap so we can dispose this one MePrint_Image = iClone() Clean Up FormGReleaseHdc(HDC1) memGReleaseHdc(HDC2)

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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 nhuSqlBase OdbcBaseetcModuleBase 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` cac 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

Cach 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 --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Tang` kernel va` usercontrol hoan` toan` dung` lai duoc Co the thuc hien multi connection ( trong cac ung dung chuyen doi database tu` Access --gt 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` cach thiet ke cua em ^^

code đệ quy duyệt toagraven bộ caacutec menu trong 1 MENUTRIP ( bất kể coacute bao nhiecircu cấp ) bạn coacute thể sửa đổi đoạn code nagravey để tạo TREE trong tree view hay GRID tham số DT lagrave 1 datatable chứa caacutec menu magrave người dugraveng được pheacutep truy cập nếu khocircng tigravem thấy thigrave menu đoacute sẽ bị disable

Private Sub ScanMenu(ByRef Menu As Object ByRef DT As DataTable) If Menu Is Nothing Then Return Dim mns As MenuStrip = TryCast(Menu MenuStrip) if first levels If mns IsNot Nothing Then For I As Integer = 0 To mnsItemsCount - 1 Dim Mi As ToolStripMenuItem = mnsItems(I) If MiDropDownItemsCount gt 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 MiDropDownItemsCount - 1 Dim subMi As ToolStripMenuItem subMi = TryCast(MiDropDownItems(I) ToolStripMenuItem) If subMi Is Nothing Then Continue For If subMiDropDownItemsCount gt 0 Then ScanMenu(subMi DT) Else

Dim X As DataRow() = DTSelect(StringFormat(AccessMenu=0 subMiText)) subMiVisible = Not (XLength = 0) End If Next End IfEnd Sub

Đoạn matilde của migravenh lagrave dugraveng đệ quy để duyet toagraven bocirc caacutec item trong menu dugraveng để - Vẽ cacircy phacircn quyền ( tree view hoặc dugraveng c1 flexgrid )- Duyet menu để phacircn quyen - thường lagrave ẩn menu đoacute đi sửa đổi 1 chuacutet cho khớp với dữ liệu của bạn Chỉ aacutep dụng cho menutrip

Tocirci cần hiển thị danh saacutech caacutec đơn hagraveng vagrave chi tiết từng đơn hagraveng trecircn 1 grid coacute bảng tblDonHang vagrave tblChiTietDonHang Thường khi lập trigravenh ta sẽ tạo ra dataset coacute 2 bảng đoacute vagrave đặt quan hệ Master - Detail thigrave việc hiện thị lagrave dễ dagraveng Dự aacuten được xacircy dựng theo phương phaacutep hướng đối tượng --gt coacute 2 lớp tương ứng lagrave clsDonHang vagrave clsChiTietDonHang 2 lớp trecircn coacute caacutec phương thức trả về dữ liệu lagrave tập caacutec object chứ khocircng cograven lagrave caacutec record necircn tocirci chưa coacute caacutech Baacutec nagraveo đatilde xử lyacute vấn đề nagravey thigrave coacute thể giuacutep tocirci xử lyacute với help me

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Thocircng thường nếu xacircy dựng caacutec lớp xử lyacute dữ liệu sẽ coacute caacutec phương thức trả về đối tượng mang dữ liệu tương ứng

Viacute dụ trong trường hợp của bạn tocirci giả sử mỗi đối tượng TABLE ( đơn hagraveng chi tiết đơn hagraveng) đều coacute caacutec phương thức sauFillData lấy dữ liệu vagrave điền dữ liệu vagraveo đối tượng bạn cung cấpGetData lấy dữ liệu vagrave trả về đối tượng tương ứng chứa dữ liệu đoacute

Coacute thể phương thức nagravey coacute dạng sau (trong trường hợp của bạn)public class ChiTietDonHangDataTable SystemDataTable

public class DonHangDataTable SystemDataTable

public class clsDonHangpublic void FillData (DonHangDataTable donhang)public DonHangDataTable GetData ()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangpublic class clsChiTietDonHangpublic void FillData(DonHangDataTable donhang)public DonHangDataTable GetData()DonHangDataTable _donhang = new DonHangDataTable()lấy dữ liệu ở đacircy return _donhangVậy trong trường hợp của bạn coacute thể xử lyacute như saupublic void InitDataSet()

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

_objDonHangFillData(_dtDonHang)_objChiTietDonHangFillData(_objChiTietDonHang)

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

_dsDonHangTablesAdd(_dtDonHang)_dsDonHangTablesAdd(_dtChiTietDonHang)

_dsDonHangRelationsAdd(new DataRelation(DonHang_ChiTietDonHang ))

Gaacuten vagraveo Lưới ở đacircy

Coacute lẽ tocirci chưa hiểu rotilde yacute bạn muốn trao đổi nhưng theo như tocirci hiểu lagrave bạn muốn sử dụng caacutec object đoacute với caacutec giaacute trị của caacutec property của noacute lecircn caacutec control vấn đề nagravey thigrave tocirci thấy NET 2 đatilde xử lyacute rồi magrave bạn chứa caacutec object đoacute trong một Listltgt sau đoacute bạn chỉ việc dugraveng list nagravey lagravem datasource nagravey cho caacutec control coacute khaacutec gigrave lagrave datatable dataview hay datareader đacircu ngoagravei ra để binding theo đuacuteng nghĩa bạn cograven coacute thể xacircy dựng caacutec phương thức để insert update vagrave delete nữa noacute cograven coacute vẻ tiện hơn lagrave sử dụng caacutec command cho caacutei adapter trước kia Thực ra sau khi dugraveng caacutei nagravey tocirci iacutet khi cograven sử dụng datatable dataview để tương taacutec dữ liệu đằng UI nữaHitting the enter key in a TextBox can sometimes have undesired effects like the wrong submit Button being ldquoclickedldquo 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 IENetscape

function clickButton(e buttonid) var evt = e e windowevent var bt = documentgetElementById(buttonid) if (bt) if (evtkeyCode == 13) btclick() return false

code behind TextBox1AttributesAdd(onkeypress return clickButton(event + Button1ClientID + ))

The code behind generates the following code

ltinput name=TextBox1 type=text id=TextBox1 onkeypress=return clickButton(eventButton1) gt

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 SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Private Sub TextBox1_TextChanged(ByVal sender As SystemObject ByVal e As SystemEventArgs)

Dim con As New SqlConnection(server=localhostuid=sapwd=DataBase=EMP)

Dim com As SqlCommand

Dim Ds As DataSet

Dim Da As SqlDataAdapter

com = New SqlCommand(SELECT FROM EMPLOYEE con)

Ds = New DataSet

Da = New SqlDataAdapter(com)

DaFill(Ds EMPLOYEE)

DataGrid1DataSource = Ds

DataGrid1DataBind()

conClose()

End Sub

Mnh coacute một form với nhiều textbox nhập liệu Để di chuyển giữa caacutec text box thigrave migravenh đặt tabindex theo thứ tự khi form hoạt động thigrave nhấn tab để di chuyển Nhưng migravenh muốn người dugraveng khi nhấn vagraveo phiacutem mũi tecircn trecircn bagraven phiacutem thigrave cũng coacute taacutec dụng như phiacutem tab Vậy sự kiện bắt phiacutem nagravey như thế nagraveoMigravenh thấy vbnet coacute hỗ trợ ekeycode ekeydata ekeyvalues migravenh ko biết caacutech dugraveng 3 caacutei nagravey thigrave khaacutec gigrave nhau Migravenh thấy caacutei ekeycode ekeydata higravenh như giống nhauampnbspVấn đề 2 Migravenh coacute một maskedtextbox để nhập liệu ngagravey thaacuteng ampnbspvagraveo hiển thị dữ liệu lecircn datagrid Sau đoacute migravenh muốn dữ liệu sẽ hiện lại lecircn maskedtextbox khi duyệt dữ liệu Nhưng với ngagravey thaacuteng vd 05022003 thigrave khi hiện lecircn maskedtextbox với hagravem định dạng Ctype(object datetime) thigrave noacute hiện lecircn lagraveampnbsp 522007__Vậy phải định dạng thế nagraveo để coacute thể hiển thị số 0 trước ngagravey thaacuteng lt10 để cho đuacuteng dạng mm

O van de 1Ban mo MSDN len tra tu SendKey

Vấn đề 2drgCell[xyz]ToString(ddMMyyyy)

Resize Control khi thay đổi độ phacircn giải của magraven higravenh

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Public Class Form1 Private Sub Form1_Load(ByVal sender As SystemObject ByVal e As SystemEventArgs) Handles MyBaseLoad Dim rec As Rectangle Dim CtlOut CtlIn As Control For Each CtlOut In MeControls CtlOutTag = CtlOutTop MeHeight amp amp CtlOutLeft MeWidth amp amp CtlOutWidth MeWidth amp amp CtlOutHeight MeHeight amp amp CtlOutFontSize MeHeight If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls CtlInTag = CtlInTop CtlOutHeight amp amp CtlInLeft CtlOutWidth amp amp CtlInWidth CtlOutWidth amp amp CtlInHeight CtlOutHeight amp amp CtlInFontSize CtlOutHeight Next End If Next MeHeight = ScreenGetBounds(rec)Height MeWidth = ScreenGetBounds(rec)Width MeTop = 0 MeLeft = 0 End Sub Private Sub Form1_Resize(ByVal sender As Object ByVal e As SystemEventArgs) Handles MeResize Dim CtlOut CtlIn As Control For Each CtlOut In MeControls ResizeControl(Me CtlOut) If TypeOf CtlOut Is GroupBox Then For Each CtlIn In CtlOutControls 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 = ChCtlTagToString P1 = ctlTagIndexOf() CtlTop = ctlTagSubstring(0 P1) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlLeft = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 P1 = ctlTagIndexOf( P2) CtlWidth = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

P1 = ctlTagIndexOf( P2) CtlHeight = ctlTagSubstring(P2 P1 - P2) P2 = P1 + 1 ctlFontSize = ctlTagSubstring(P2) ChCtlTop = PaCtlHeight CtlTop ChCtlLeft = PaCtlWidth CtlLeft ChCtlHeight = PaCtlHeight CtlHeight ChCtlWidth = PaCtlWidth CtlWidth ChCtlFont = New Font(ChCtlFontName CSng(PaCtlHeight ctlFontSize) ChCtlFontStyle) End Sub End Class

-----Sub AutoSize(ByVal Form1 As Variant)On Error Resume NextIf ScreenWidth ltgt 12000 And ScreenHeight ltgt 9000 Then Dim i As Long Dai As Single Rong As Single Dai = ScreenWidth Rong = ScreenHeight Form1Width = Form1Width (12000 Dai) Form1Height = Form1Height (9000 Rong) For i = 0 To Form1ControlsCount - 1 Form1Controls(i)Top = Form1Controls(i)Top (12000 Dai) Form1Controls(i)Left = Form1Controls(i)Left (9000 Rong) Form1Controls(i)Width = Form1Controls(i)Width (12000 Dai) Form1Controls(i)Height = Form1Controls(i)Height (9000 Rong) Form1Controls(i)AutoSize = True Next iEnd IfErrClearEnd 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 khocircng thể duy chuyển đượcBạn muốn tạo một form chiếm giữ một vị triacute cố định trecircn magraven higravenh vagrave khocircng thể di chuyển được Tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Hoặc bạn coacute thể hiện thực thuộc tiacutenh Moveable cho form Bạn coacute thể tạo một form khocircng-đường-viền bằng caacutech thiết lập thuộc tiacutenh FormBorderStyle lagrave None Caacutec form thế nagravey khocircng thể di chuyển được Vagrave chuacuteng nếu muốn coacute đường viền bạn phải viết matilde lệnh vẽ hoặccũng thiếu mất đường viền sử dụng higravenh nền Coacute một caacutech khaacutec để tạo một form khocircng thể di chuyển được vagrave form nagravey coacute đường viền giống điều kiểm Trước tiecircn thiết lập caacutec thuộc tiacutenh ControlBox MinimizeBox vagrave MaximizeBox lagrave False Kế tiếp thiết lập thuộc tiacutenh Text lagrave chuỗi trống Khi đoacute form sẽ coacute đường viền nổi magraveu xaacutem hoặc đường kẻ magraveu đen (tugravey thuộc vagraveo tugravey chọn FormBorderStyle magrave bạn sử dụng) tương tự như Button Phần dưới đacircy sẽ trigravenh bagravey một caacutech tiếp cận khaacutec hiện thực thuộc tiacutenh Moveable cho form (trong Visual Basic 6 form coacute thuộc tiacutenh Moveable nhưng trong NET thuộc tiacutenh

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

nagravey khocircng cograven nữa) Trước tiecircn chuacuteng ta xacircy dựng lớp ImmoveableForm như sau (thừa kế từ [vb]SystemWindowsFormsForm)

Public Class ImmoveableForm Inherits SystemWindowsFormsForm

Private Declare Function EnableMenuItem Lib user32dll _ Alias EnableMenuItem (ByVal hMenu As IntPtr _ ByVal uIDEnableItem As Int32 ByVal uEnable As Int32) As Int32

Private Const HTCAPTION As Int32 = ampH2

Private Const MF_BYCOMMAND As Int32 = ampH0amp Private Const MF_ENABLED As Int32 = ampH0amp Private Const MF_GRAYED As Int32 = ampH1amp Private Const MF_DISABLED As Int32 = ampH2amp

Private Const SC_MOVE As Int32 = ampHF010amp

Private Const WM_NCLBUTTONDOWN As Int32 = ampHA1 Private Const WM_SYSCOMMAND As Int32 = ampH112 Private Const WM_INITMENUPOPUP As Int32 = ampH117amp

Private bMoveable As Boolean = True

Public Sub New() MyBaseNew() End Sub

ltSystemComponentModelCategory(Behavior) _ SystemComponentModelDescription(Allows the form to be moved)gt _ Public Overridable Property Moveable() As Boolean Get Return bMoveable End Get Set(ByVal Value As Boolean) If bMoveable ltgt Value Then bMoveable = Value End If End Set End Property

Protected Overrides Sub WndProc( _ ByRef m As SystemWindowsFormsMessage) If mMsg = WM_INITMENUPOPUP Then Thụ lyacute việc hiển thị menu hệ thống

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

If mLParamToInt32 65536 ltgt 0 Then Dim AbleFlags As Int32 = MF_ENABLED If Not Moveable Then AbleFlags = MF_DISABLED Or MF_GRAYED EnableMenuItem(mWParam SC_MOVE _ MF_BYCOMMAND Or AbleFlags) End If End If

If Not Moveable Then If mMsg = WM_NCLBUTTONDOWN Then Khocircng cho pheacutep keacuteo recirc cửa sổ bằng thanh tiecircu đề If mWParamToInt32 = HTCAPTION Then Return End If End If If mMsg = WM_SYSCOMMAND Then Vocirc hiệu chức năng Move trecircn menu hệ thống If (mWParamToInt32 And ampHFFF0) = SC_MOVE Then Return End If End If End If MyBaseWndProc(m) End Sub

End Class[vb]

Để sử dụng lớp trecircn bạn cần hiệu chỉnh phần matilde 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() MyBaseNew()

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

Add any initialization after the InitializeComponent() call

Vocirc hiệu khả năng di chuyển form của người dugraveng MeMoveable = False End Sub

(Bỏ qua phần matilde cograven lại)

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

End Class[vb]

Sau đoacute chức năng bị vocirc hiệu hoacutea

Triacutech từ Caacutec giải phaacutep lập trigravenh VISUAL BASIC NET (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Caacutech để xaacutec minh matilde số saacutech coacute hợp lệ hay khocircng trong VBNetXaacutec nhận tiacutenh hợp lệ của ISBN

Bạn muốn xaacutec minh một ISBN (International Standard Book Number matilde số saacutech chuẩn quốc tế) coacute hợp lệ hay khocircng Tiacutenh vagrave kiểm tra bằng pheacutep Mod 11 Trong trường hợp nagravey bạn nhacircn mỗi chữ số với vị triacute của noacute (ngoại trừ số cuối cugraveng) cộng những số nagravey với nhau vagrave kiểm tra phần dư của tổng chia cho 11 coacute trugraveng với chữ số cuối cugraveng hay khocircng Dưới đacircy lagrave hagravem magrave bạn coacute 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 valueLength - 2 CheckSum += IntegerParse(valueChars(i)) (i + 1) Next Dim CheckDigit As Integer CheckDigit = IntegerParse(valueChars(valueLength - 1)) Return (CheckSum Mod 11 = CheckDigit) End Function[vb] Bạn coacute thể thử nghiệm hagravem nagravey như sau [vb]If ValidateISBN(1861007353) Then Đacircy lagrave ISBN hợp lệ End If[vb] Nhớ rằng phương thức nagravey giả sử mọi dấu ldquo-rdquo đatilde bị loại khỏi chuỗi Nếu khocircng chắc bước nagravey đatilde được thực hiện hay chưa bạn coacute thể viết thecircm matilde để loại bỏ hoặc bỏ qua dấu ldquo-rdquo

Triacutech từ Caacutec giải phaacutep lập trigravenh Visual Basic Net (tập 1) httpwwwdvpubcomvndvdetailsaspxitemid=244Matilde hoacutea password Tocirci muốn matilde hoacutea password trước khi chegraven vagraveo DB khocircng biecirct bạn nagraveo đatilde từng lagravem coacute thể giuacutep tocirci trong code VBNET được khocircngBạn coacute thể dugraveng code sauCode

Private Function Mahoa(ByVal pass As String) As String Dim uEncode As New UnicodeEncoding Dim result As Byte() = uEncodeGetBytes(pass) Dim md5 As New MD5CryptoServiceProvider result = md5ComputeHash(result) Return ConvertToBase64String(result)

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

End Function

Vagrave import thecircm caacutei nagravey lagrave ok SystemSecurityCryptographyĐối số trong sự kiện VBNET Trong bagravei nagravey tocirci xin noacutei về hai đối số magrave coacute mặt trong mọi sự kiện của VBNet Một đối số gửi thocircng tin về đối tượng vagrave một đối số gửi thocircng tin về hagravenh động magrave gacircy ra sự kiệnHai đối số đoacute lagrave sender vagrave e Đacircy lagrave khai baacuteo của sự kiện Click cho một nuacutet[HIGHLIGHT=vb]Private Sub Button1_Click(ByVal sender As SystemObject _ByVal e As SystemEventArgs) Handles Button1ClickEnd Sub[highlight]Đối số sender lưu thocircng tin về đối tượng magrave gacircy ra sự kiện chuacuteng ta sử dụng đối số nagravey để xaacutec định kiểu của đối tượng magrave sinh ra sự kiện Viacute dụ[HIGHLIGHT=vb]ConsoleWriteLine(senderToString)SystemWindowsFormsButton Text Button1ConsoleWriteLine(senderGetType)SystemWindowsFormsButton[highlight]Đối số thứ hai e chứa mọi thocircng tin magrave bạn cần để xử lyacute sự kiện Đối tượng e coacute một vagravei thuộc tiacutenh magrave phụ thuộc vagraveo kiểu của sự kiện vagrave điều khiển sinh ra sự kiện Thocircng tin magrave bạn cần thiết để xử lyacute caacutec kiểu sự kiện được truyền qua đối nagraveySự kiện chuộtDatildey caacutec sự kiện chuột xảy ra khi bạn nhấn chuột thứ tự của chuacuteng lần lượt lagrave MouseDown Click vagrave MouseUp Sự kiện chuột xảy ra ngay cả khi bạn di chuyển chuột qua caacutec điều khiển sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vagraveo điều khiển datildey caacutec sự kiện MouseMove xảy ra khi di chuột trecircn điều khiển sau đoacute lagrave sự kiện MouseHover vagrave MouseLeave xảy ra khi chuột rời khỏi điều khiển Mặc dugrave caacutec sự kiện khaacutec nhau nhưng chuacuteng cugraveng gửi thocircng tin cho ứng dụng qua đối e vagrave bạn coacute thể khai thaacutec vagravei thuộc tiacutenh của đối e nagravey để sử dụng trong chương trigravenh của migravenhButton trả lại một hằng tượng trưng cho nuacutet được nhấn vagrave nhận giaacute trị thuộc tập hằng kiểu liệt kecirc MouseButtons Left Middle None Right XButton1 vagrave XButton2 Hai giaacute trị cuối cugraveng dugraveng cho kiểu chuột năm nuacutet vagrave tương ứng với hai nuacutet ở hai becircn cạnh Tuy nhiecircn đối e trong sự kiện Click hoặc DblClick khocircng cung cấp thuộc tiacutenh Button vigrave hai sự kiện nagravey chỉ được thực hiện với nuacutet chuột traacuteiClicks trả về số lần chuột được nhấn vagrave thả chỉ nhận giaacute trị 1 hoặc 2Delta thuộc tiacutenh được dugraveng với chuột coacute nuacutet cuộn trả về số lần nuacutet cuộn được quay Bạn coacute thể dugraveng thuộc tiacutenh nagravey để biết hộp Textbox đatilde được cuộn như thế nagraveoXY trả lại toạ độ của chuột luacutec chuột được nhấn hoặc được thả Toạ độ chuột được tiacutenh theo toạ độ tương đối của điều khiển liecircn quan theo pixel Nếu bạn nhận chuột ở goacutec traacutei trecircn của một nuacutet thigrave toạ độ trả về sẽ lagrave 00Sự kiện bagraven phiacutemCaacutec điều khiển magrave nhận caacutec text thường coacute nhiều sự kiện bagraven phiacutem viacute dụ như điều khiển TextBox Sự kiện KeyPress xảy ra khi một phiacutem được nhấn cograven sự kiện KeyDown vagrave KeyUp xảy ra khi một phiacutem được nhấn vagrave thả tương ứng Sau đacircy lagrave khai baacuteo của sự kiện KeyDown của TextBox[HIGHLIGHT=vb]Private Sub TextBox1_KeyDown(ByVal sender As Object ByVal e As_ SystemWindowsFormsKeyEventArgs) Handles TextBox1KeyDownEnd Sub[highlight]Đối thứ hai cung cấp thocircng tin về trạng thaacutei bagraven phiacutem vagrave phiacutem được nhấn thocircng qua caacutec thuộc tiacutenh của noacuteAlt Control Shift ba thuộc tiacutenh trả về giaacute trị TrueFalse xaacutec định phiacutem điều khiển tương ứng được nhấn khi phiacutem được nhấnKeyCode trả về matilde phiacutem được nhấn vagrave lagrave một giaacute trị thuộc tập hằng liệt kecirc Keys Tập hằng nagravey chứa giaacute trị cho mọi phiacutem viacute dụ kiacute tự a vagrave A đều coacute matilde lagrave KeysA

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

matilde của phiacutem 0 becircn keypad lagrave Key0 phiacutem F1 lagrave KeyF1 Vagravei phiacutem điều khiển như NumLock ScrollLock WakeUp vagrave Sleep luocircn trả về KeyCode bằng 0KeyData trả về giaacute trị long xaacutec định phiacutem được nhấn noacute cũng tương tự như thuộc tiacutenh KeyCode nhưng phacircn biệt kiacute tự vagrave kiacute hiệu trecircn phiacutemKeyValue trả lại giaacute trị cho phiacutem được nhấn thường thigrave cugraveng giaacute trị như KeyData chỉ khaacutec biệt ở caacutec phiacutem điều khiển--------------Translate from Mastering VBNETThecircm sửa trugraveng matilde

Em muốn hỏi khi thecircm dữ liệu ở bảng coacute khoaacute chiacutenh coacute kiểu nchar

thigrave khi thecircm hay sửa dữ liệu coacute thể dẫn đến trugraveng matilde

gacircy lỗi

Vậy cần phải coacute thủ tục kiểm tra khoaacute chiacutenh

thocircng baacuteo nếu trugraveng thigrave khocircng cho thecircm

nếu trugraveng thigrave khocircng cho sửa

Trong trường hợp nagravey Em necircn sử dụng thecircm một matilde nữaMatilde nagravey chiacutenh lagrave matilde sẽ thay đổi do người dugraveng nhậpVagrave trong thủ tục SQL Em viết như sau

ALTER PROCEDURE sp_Insert_UpdateID nvarchar(15)Ma nvarchar(15)IF EXISTS (SELECT Ma FROM TenBang WHERE Ma=Ma And IDltgtID) Begin Insert End ELSE Begin Update End

Để đưa dữ liệu từ bảng khaacutec lecircn Combo Em lagravem như sau nheacute

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

ALTER PROCEDURE SP_Select_Branch

AS

Select from Branch

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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

Public Shared Sub ReturnDataAdapter(ByVal strSP As StringByVal objConn As SqlConnection) As SqlDataAdapter Try Make a comman object for stored procedure Dim cmd As New SqlCommand(strSP objConn) cmdCommandType = CommandTypeStoredProcedure Dim adt As New SqlDataAdapter(cmd) Return adt Catch ex As Exception MsgBox(Error amp exMessageToString MsgBoxStyleOKOnly Thong Bao 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 BooleanByVal 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(sqlstrobjConn ) datAdapterFill(datDsCB) datAdapterDispose() 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 myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboDisplay dua cot vao bang

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

datTableColumnsAdd(myDataColumn) cot thu 1 myDataColumn = New DataColumn myDataColumnDataType = TypeGetType(SystemString) myDataColumnColumnName = cboValue dua cot vao bang datTableColumnsAdd(myDataColumn) them mot dong myDataRow = datTableNewRow myDataRow(cboValue) = myDataRow(cboDisplay) = dua dong vao bang datTableRowsAdd(myDataRow) If datDsCBTables(0)RowsCount gt 0 Then For i = 0 To datDsCBTables(0)RowsCount - 1 myDataRow = datTableNewRow myDataRow(cboValue) = datDsCBTables(0)Rows(i)Item(cboValue) myDataRow(cboDisplay) = datDsCBTables(0)Rows(i)Item(cboDisplay) dua dong vao bang datTableRowsAdd(myDataRow) Next End If Dua bang vao Dataset datDsCBTablesAdd(datTable) gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(datTableTableName) Else Neu khong null gan gia tri nguon cho Combo cboNameDataSource = datDsCBTables(0) End If cot dua vao gia tri nho cua combo cboNameValueMember = Trim(cboValue) dua dl tu cot de hien thi tren combo cboNameDisplayMember = Trim(cboDisplay) Catch ex As Exception MsgBox(exToString) End Try End Sub

Trecircn Form Em goi như sau

GetData_Into_Cbo(SP_Select_BranchcboBranchBranchIDBranchNameFalseConn)

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Trong đoacute SP_Select_Branch lagrave tecircn thủ tục Em viết trong SQLcboBranch lagrave tecircn ComboConn lagrave đối tượng kết nối

Bạn đatilde tạo được giao diện XP trong VBNET 2003 chưa Chắc lagrave chưa đuacuteng khocircng

Nếu chưa tạo được bạn hatildey lagravem theo caacutec bước sau đacircy đảm bảo sẽ coacute giao diện XP

Sau khi bạn keacuteo vagrave thả caacutec đối tượng vagraveo Form bạn vagraveo Properties tiếp đến bạn chọn thuộc tiacutenh FlatStyle lagrave System (Tất nhiecircn sẽ coacute một số đối tượng khocircng coacute thuộc tiacutenh nagravey viacute dụ như ComboBox chẳng hạn nhưng migravenh khocircng cần quan tacircm noacute sẽ tự động nhận)

Sau đoacute bạn tải File XPEXEmanifest rồi đổi tecircn XP thagravenh tecircn dự aacuten của bạn vagrave vất vagraveo thư mục chứa File EXE lagrave xong

Cụ thể lagrave Giả sử dự aacuten của bạn tecircn lagrave KT (KT lagrave tecircn hiện trong Exploer Solution) bạn sẽ đổi như sau Đổi XPEXEmanifest thagravenh KTEXEmanifest rồi vất vagraveo thư mục chứa EXE

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

File điacutenh kegravem(s)XPEXEmanifest (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 tenluoirefesh() nhung cung ko nhan Co can phai viet them doan lenh nao ko a

Em dugraveng cacircu lệnh tenluoirefesh() thigrave chưa đủ đacircu

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 thagravenh cocircng lagrave xong

GetDataGird() nằm trong sự kiện khi click chuột vagraveo nuacutet Cập nhật Em aTrong VBNET việc đưa dữ liệu ra DataSet thigrave quả lagrave đơn giản đuacuteng khocircng Những liệu bạn đatilde biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thocircng tin cần thiết chưaĐiều nagravey thigrave chắc khocircng phải ai cũng biết

Tối lấy một trường hợp thế nagraveyGiả sử tocirci coacute một DataSet chứa dữ liệu của bảng KhachHang với caacutec trường MaKHTenKHBacircy giờ tocirci muốn lấy ra những khaacutech hagraveng coacute matilde gt10 Đacircy chiacutenh lagrave truy vấn dữ liệu trong DataSet

Tocirci xin giới thiệu với chuacuteng ta một caacutech lagravem như sau

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

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Dim da As SqlDataAdapterDim ds As DataSet=New DataSetdaFill(dsKhachHang)Chuacuteng ta lagravem như sau

Đầu tiecircn chuacuteng ta khai baacuteo một DataRow

Dim RowMaKH As DataRow()RowMaKH= dsTables(KhachHang)Select(MaKH gt10)

Như vậy RowMaKH sẽ chứa toagraven bộ những khaacutech hagraveng coacute matilde gt10

Để lấy giaacute trị thứ i trong RowMaKH bạn chỉ cần dugraveng cacircu lệnh RowMaKH(i)Item(MaKH)cach nao de co combobox tren luoi flexgridCoacute hai trường hợp xảy ra

Một do người dugraveng định nghĩa vagrave tạo thagravenh ComboBox Giả sử Thầy muốn tạo ra combobox coacute nam vagrave nữTrường hợp nagravey ta lagravem như sau

Dim slist As SortedList slist = New SortedList slistAdd(True Nam) slistAdd(False Nữ) GirdNameCols(TenCot)DataMap = slist

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

Trường hợp nagravey sẽ lagravem như sauĐầu tiecircn viết một hagravem

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)

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

datSqlAdapterFill(datDs cboTable) datSqlAdapterDispose() If datDsTables(cboTable)RowsCount gt 0 Then For i = 0 To datDsTables(cboTable)RowsCount - 1 slistAdd(Trim(datDsTables(cboTable)Rows(i)Item(sKey)ToString) Trim(datDsTables(cboTable)Rows(i)Item(sValue))) Next End If datDsDispose() Return slist Catch ex As Exception MsgBox(exToString) datDsDispose() 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) GrdNameCols(TenCot)DataMap = slistsp_Select lagrave cau sql lay du lieu tu bang

Caacutec đoạn nagravey sẽ được đặt sau GetDataGird() vagrave trong FormatGird() Em thecircm cacircu lệnh GirdNameAllowEditing=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 ngagravey thaacuteng Em khocircng necircn dugraveng đối tượng TextBox magrave necircn dugraveng đối tượng DateTImePicker Mặc định sẽ coacute dữ liệu ngagravey thaacuteng Nếu cố tigravenh khocircng nhập thigrave vẫn coacuteCograven nếu Em dugraveng TextBox thigrave chỉ cần kiểm tra If TextBoxText= then MessageBoxShow(Bạn chưa nhập ngagravey sinh)

Thứ 2 Để kiểm soaacutet được vấn đề khoaacute ngoại vagrave khoaacute chiacutenh như vậy thigrave rất đơn giản Em lagravem như sau nheacute

Em xem trường khoaacute ngoại đoacute coacute cho pheacutep Null hay khocircngNếu cho pheacutep Null thigrave khocircng

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

cần quan tacircm đến trường khoaacute chiacutenh coacute dữ liệu hay khocircngCograven nếu khocircng cho pheacutep Null thigrave khi Em dưa dữ liệu từ bảng coacute khoacutea chiacutenh lecircn Combo để chọn thigrave Em mặc định cho Combo coacute dữ liệu lagrave xongKể cả khi người dugraveng khocircng chọn thigrave mặc định vẫn coacute dữ liệu lam the nao de co checkbox hien len tren luoiTuỳ thuộc vagraveo cột nagraveo Em cần coacute CheckBox thigrave Em sẽ cho lagravem CheckBox vagrave chỉ cần dugraveng thuộc tiacutenh DataType

Viacute dụ Em cần cho cột GioiTinh lagrave CheckBox Em dugraveng cacircu lệnh

GrdNameCols(GioiTinh)DataType=GetType(Boolean)GrdNameCols(GioiTinh)AllowEditing=True

GrdName lagrave tecircn lướiGioiTinh Lagrave cột cần lagrave CheckBox

Đoạn Code trecircn Em cho vagraveo phần FormatGird()Lam sao em tao truong ngay thang len luoi ko duoc (tren luoi ko co truong ngay thang)Đuacuteng vậy trecircn lưới khocircng coacute trường ngagravey thaacutengĐể coacute trường ngagravey thaacuteng Em phải viết một đoạn Code Đoạn code nagravey sẽ nằm trong phần FormatGird()

Tuỳ thuộc vagraveo cột nagraveo Em muốn cho lagrave ngagravey thaacuteng magrave viết code tương ứng vagrave dugraveng thuộc tiacutenh DataType

Viacute dụ Em muốn cột ngagravey sinh (NgaySing) lagrave ngagravey thaacutengEm lagravem như sau

GrdNameCols(NgaySinh)DataType=GetType(DataTime)GrdNameCols(NgaySinh)AllowEditing=TrueGrdName Lagrave tecircn lướiNgaySinh Lagrave cột ngagravey sinh sẽ hiện trecircn lưới

1 Em muốn hỏi ta coacute bảng Khoa coacute matilde khoa lagrave duy nhất khocircng trugraveng

lagravem thế nagraveo sau khi thecircm nếu trugraveng matilde khoa

thigrave thocircng baacuteo matilde khoa nagravey đatilde tồn tại rồi

2 Thủ tục sp_Insert_Update_mFaculty phải sửa như thế nagraveo ạ

3 Code chương trigravenh phải sửa như thế nagraveo ạ

Để lagravem được điều nagravey thigrave trong thủ tục sp_Insert_Update_mFaculty Em thecircm 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 END

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

KT bit output

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

Trong Code cung thecircm một tham số KT như sau

Dim Param as SqlParameter() = New New SqlParameter(KTSlqDataTypeBit)

Param(0)Value=Param(5)Direction=ParameterDirectionOutput Tham số KT giả sử lagrave thứ 5

RunSP(sp_Insert_Update_mFaculty cnnParam)

If Param(5)Value=True then MessageBoxShow(Matilde bạn vừa nhập đatilde tồn tạiĐề nghị bạn nhập matilde khaacutec)End If

Lagravem thế nagraveo magrave khi Nhấn vagraveo tigravem kiếm nếu thấy thigrave

Lưới nhảy đến dograveng tigravem thấy vagrave caacutec ocirc textbox nhảy theo

Em đatilde thử rồi chỉ lagravem được với textbox nhưng lưới khocircng được

Để lagravem được điều nagravey Em chỉ cần dugraveng thuộc tiacutenh Select lagrave được Cụ thể như sau

If txtHoTenTextltgt then For i as integer=0 to grdNameRowsCount -1 If txtHoTenText=grdName(iHoTen) then grdNameSelect(iTrue) Dograveng tigravem thấy được chọn End If

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

NextEnd if

Khi coacute lệnh grdNameSelect(iTrue) nagravey lập tức caacutec TextBox trecircn Form sẽ hiển thị dữ liệu tương ứng trecircn lưới thocircng qua sự kiện grdName_EnterCell()

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

Em đatilde Cho thuộc tiacutenh ToMost của Form Login bằng True

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

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

Trong UltraToolBar em đatilde đặt thuộc tiacutenh IsMenuBar lagrave True

Vagrave Trong Form Main Em đatilde đặt thuộc tiacutenh Lagrave Form Chiacutenh

Khocircng hiểu sao lại khocircng được

Vậy Em thử thế nagravey nheacute

Trong form Main khi Em gọi form Login Em dugraveng thuộc tiacutenh Show() thay cho ShowDialog()

frmLoginShow()

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 xoacutea Group kể cả thecircm Button hoặc Toolbar khi Click chuột phải vagraveo thực chất chỉ lagrave ảoTức lagrave những cocircng việc đoacute chỉ tồn tại vagrave coacute hiệu lực trong thời gian migravenh chạy phần mềm thocirci vagrave khi migravenh thoaacutet phần mềm rồi chạy lại thigrave những mục migravenh đatilde Thecircm Xoaacute vẫn tồn tại

Em thử chạy Office 2003 magrave xem Noacute cũng cho migravenh thecircmxoacutea caacutec mục trecircn menu những khi chạy lại thigrave vẫn cograven những caacutei migravenh đatilde xoaacute

Migravenh necircn để người dugraveng thay đổi Panel Em ạ Vigrave khi độ phacircn giải magraven higravenh thay đổi thigrave

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Panel sẽ được thay đổi theoNếu migravenh quản lyacute noacute khocircng cho noacute thay đổi thigrave khocircng hay đacircu

Việc quản lyacute Thecircm xoacutea cũng coacute thể quản lyacute được nhưng migravenh cứ để cho người dugraveng thecircm xoacutea khocircng sao Em ạ

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

Trong VBNET coacute 2 caacutech truyền caacutec tham số vagraveo caacutec phương thức (Thủ tục hoặc hagravem) lagrave ByVal (Truyền theo tham trị) vagrave ByRef (Truyền theo tham chiếu) Hai caacutech dugraveng nagravey hoagraven toagraven khaacutec nhau chứ khocircng phải giống nhau như Em nghĩ vagrave trong VBNET mặc định khi lập trigravenh viecircn truyền caacutec tham số vagraveo caacutec phương thức noacute sẽ lagrave ByVal Thocircng thường thigrave necircn dugraveng ByVal

Em để yacute viacute dụ sau thigrave sẽ hiểu nheacute

Private FunctionTinhTong(ByVal a As IntegerByVal 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 lagrave ByVal thigrave sau khi gọi ThayTheByVal(Tong) thigrave kết quả vẫn lagrave 10 Nhưng nếu lagrave ByRef thigrave sau khi goi ThayTheByRef(Tong) thigrave kết quả lại lagrave 5

Em đọc kỹ rồi sẽ hiểu Toacutem lại lagrave Khi truyền bằng ByVal thigrave noacute sẽ khocircng bị thay đổi becircn trong phương thức cograven khi truyền bằng ByRef thigrave noacute sẽ bị thay đổi becircn trong phương thức

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Thầy cho em hỏi caacutec nuacutet di chuyển ( Về đầu Về Cuối Về Trước Về Sau vagrave cả nuacutet Huỷ bỏ thao taacutec nữa ) phải viết code cho no thế nagraveo

Em viết như sau nhưng khocircng được

MeBindingContext(dsTables(mSchool))Position=0 Về đầu

MeBindingContext(dsTables(mSchool))Position - = 1 Về trước

MeBindingContext(dsTables(mSchool))Position + = 1 Về sau

MeBindingContext(dsTables(mSchool))Position = MeBindingContext(dsTables(mSchool))Count - 1 Về cuối

Em lagravem như vậy nhưng khocircng được thầy ạ

Em lagravem thế nagravey lagrave sai rồi Khocircng được lagrave đuacuteng rồi

Em lagravem như thế nagravey nheacute

Phương thức dugraveng để nhảy xuống dograveng tiếp theo

Private Sub RowNext() grdNameFocus() If grdNameRowSel lt grdNameRowsCount - 1 Then Nếu khocircng phải lagrave cuối grdNameSelect(grdNameRowSel + 1 True) Else grdNameSelect(grdNameRowSel True) Nếu lagrave cuối End If End SubEm dang lam bang QHnhung khi ket noi voi CSDL thi bi thong boa loiVay thay hay chi cho em ve thu thuc ket noi voiQuacutea trigravenh kết nối như sau

Đầu tiecircn Em Imports 2 thư viện SystemDataSystemDataSqlClient

Sau đoacute Dim strConn As String=Server=TenMay DataBase=TenDataBase User ID =sa Password=sa Dim ObjConn As SqlConnection=New SqlConnection(strConn) ObjConnOpen()

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 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

SoCT char(10) MaK char(10) NgayTT datetime SoTien float CT2 SoCT char(10) MaHang char(10) MaNV char(10) Bảng CT1 vagrave CT2 liecircn kết 1-1

Trong nuacutet lưu em viết

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

param(0)value=metxtSoCTtext

param(1)value=mecboMaKselectedvalue

param(2)value=meNgayTTtext

param(3)value=metxtSoTientext

param(4)value=mecboMaHangselectedvalue

param(5)value=mecboMaNVselectedvalue

clsDataBaseRunSP(Insert_CTcnnparam)

getdatagird()

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

trong thủ tục Insert_CT

alter proc Insert_CT

SoCT char(10)MaK char(1)NgayTT DateTimeSoTien floatMaHang char(10)MaNV char(10)

as

begin transaction CT1

begin transaction CT2

begin

insert into CT1 values(SoCTNgayTTMaKSoTien)

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

insert into CT2 values(SoCTMaHangMaNV)

end

if(errltgt0)

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

em chạy thigrave noacute baacuteo lỗi

SoCT is not a parameter for procedure Insert_CT

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

Em để yacute nheacute

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Tất cả caacutec tham số đều khocircng coacute Em phải lagravem như sau

dim param as sqlparameter()=new sqlparameter(SoCTsqldbtypechar)new sqlparameter(MaKsqldbtypechar)new sqlparameter(NgayTTsqldbtypedatetime)new sqlparameter(SoTiensqldbtypefloat)new sqlparameter(MaHangsqldbtypechar)new sqlparameter(MaNVsqldbtypechar)

Nếu khocircng coacute chắc chắn sẽ baacuteo 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 giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

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

Thầy giuacutep em nha

Em khocircng necircn viết Insert vagraveo 2 bảng bằng một thủ tục Em necircn viết bằng TRIGER thigrave tốt hơnThầy hướng dẫn cho em caacutech lagravem một form tigravem kiếm sinh viecircn kết qủa hiện thị trecircn Grid (tigravem kiecircm theo tecircn trong bảng mStudents)Em đưa đoạn Code sau vagraveo sự kiện tigravem kiếm nheacute

Private Sub cmdTimKiem_Click( ByVal sender As Object ByVal e As SystemEventArgs) Handles cmdTimKiemClickIf grdNameRowsCountgt0 Then Nếu lưới coacute dữ liệu If txtHotenTextltgt then Nếu họ tecircn khocircng trống For i as integer =0 to grdNameRowsCount-1 If txtHotenText=grdName(iHoTen) Then Nếu tồn tại grdNameSelect(iTrue) Exit Sub End If Next End If End If

End SubMigravenh coacute 1 treeview 1 nuacutet cha vagrave 1 nuacutet con coacute 2 contextmenu Migravenh khocircng biết caacutech lagravem thế nagraveo để khi nhấn chuột phải vagraveo nuacutet cha thigrave hiện contextmenu1 nhấn vagraveo nuacutet con thigrave hiện lecircn contextmenu2Giải thuật lagrave bạn bắt sự kiện MouseDown nếu lagrave chuột phải thigrave kiểm tra node dưới con trỏ chuột lagrave parent hay child rồi show menu tương ứngCode demo lagrave C bạn chịu khoacute convert sang VBEET

private void treeView1_MouseDown(object sender SystemWindowsFormsMouseEventArgs e)if (eButton == MouseButtonsRight) Chuột phảiTreeNode node = treeView1GetNodeAt(eX eY)if (node == null) return

if (nodeParent == null)thiscontextMenu1Show(treeView1 new Point(eX eY))elsethiscontextMenu2Show(treeView1 new Point(eX eY))MessageBoxShow(nodeParentText)khi tocirci muốn sử dụng caacutec hagravem string như right leftthigrave phải khai baacuteo khocircng gian tecircn như thế nagraveo (System)

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name

Bạn dugraveng namespace nagraveyImports MicrosoftVisualBasicVagrave gọi hagravem như sauDim str As String = test stringstr = MicrosoftVisualBasicLeft(str 1)Nếuimport thigrave khocircng cần khai baacuteo MicrosoftVisualBasicvagrave ngược lại nếu khai baacuteo thigrave chỉ việc sử dụng Left(string string_len)Tocirci dugraveng mocirct file CSDL tạm để nạp dữ liệu cần in hoacutea đơn baacuten hagraveng Mỗi khi in cho khaacutech mới thigrave phải xoacutea dữ liệu đatilde in cho khaacutech hagraveng trước đoacute Nhưng lagravem sao để xoacutea nội dung file đoacute cho nhanh (khocircng phải xoacutea từng dograveng) Tocirci sử dụng CSDL Access sử dụng kết nối OleDb Mong caacutec bạn chỉ dugravemNếu chương trigravenh của bạn hỗ trợ xử lyacute truyền thẳng cacircu lệnh SQL tới DB để chạy thigrave bạn coacute thể truyền cacircu lệnh DELETE tới DB để xoaacute caacutec recordCograven khocircng bạn coacute thể lagravem 1 vograveng lặp để xoaacute caacutec record của bạnSử dụng kết nối vagrave đối tượng Command thiacutech hợp rồi truyền thằng cho noacute một cacircu lệnh SQL

Delete from tecircn_bảng (MySQL) caacutec cơ sở dữ liệu khaacutec lagrave delete from tecircn_bảng Nếu

bạn muốn xoacutea tất cả nội dung của file đoacute magrave khocircng phải lagrave xoacutea nội dung một bảng thigrave bạn

truyền cacircu lệnh SQL Drop TABLE tecircn_bảng nhưng lần sau thigrave bạn sẽ lại phải khởi tạo lại

bảng đấy

Cảm ơn bạn tocirci cũng đatilde lagravem đựoc như vậy rồi Nhưng coacute vấn đề phaacutet sinh lagrave cần xaacutec định xem Table đoacute coacute tồn tại trong Database khocircng Nếu Table đoacute ko tồn tại magrave Drop Table thigrave sẽ baacuteo lỗi ngược lại nếu Table đatilde coacute magrave dugraveng Create Table hoặc SELECT INTO Table thigrave noacute cũng baacuteo lỗi

  • Dynamic Menu Class coding
  • Dynamic Menu Form coding
  • SQL Data Provider VBNET Class - The Class
    • The Class
      • 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
          • For more information about connection strings visit ConnectionStringscom
            • ExecuteNonQuery Method
              • Executes a Transact-SQL statement against the connection and returns the number of rows affected
              • If you are using stored procedureyou can execute that without declaring parameters such as following code
                • 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
                    • ExecuteReader Method
                      • Sends the CommandText to the Connection and builds a SqlDataReader
                      • There is a sample for using stored procedure
                        • Using Return Value Parameter
                          • If you are using stored procedureyou can get the value of return value parameter
                            • FillDataset Method
                              • Adds or refreshes rows in the SystemDataDataSet to match those in the data source using the SystemDataDataSet name and creates a SystemDataDataTable named Table
                              • Binding a DataGridView with FillDataset method
                                • ExecuteDataset Method
                                  • Calls the respective INSERT UPDATE or DELETE statements for each inserted updated or deleted row in the SystemDataDataSet with the specified SystemDataDataTable name