Professional Documents
Culture Documents
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
Lấy khoảng thời gian giữa thời điểm (bắt đầu làm gì đó) và thời điểm kết
thúc :
Private Function GetDuration(ByVal timeStart As DateTime) As String
timeEnd = DateTime.Now()
timeDifference = timeEnd.Subtract(timeStart)
timeElapsed = timeElapsed.Add(timeDifference)
Return timeElapsed.ToString()
End Function
Implementation
timeStart = DateTime.Now()
Me.lblDuration.Text = GetDuration(timeStart)
[vb]Imports System.Runtime.InteropServices
Imports System.Drawing
Imports System.Drawing.Drawing2D
Về vấn đề này, bạn có thể dùng một mảng datarow để lọc những dòng thỏa
điều kiện, bạn làm như vầy:
Dim dr as datarow()
dr=ds.Tables("Mathang").Select("Mahang like '" & mahang & "*'")
Cách cài đặt 1 ứng dụng VB2005.NET trên mạng LAN như thế nào
Tôi có 1 ứng dụng viết bằng VB.NET. Khi chạy ứng dụng trên máy cài đặt
chương trình thì nó hoạt động bình thường. Tôi có tạo một shortcut đến
chương trình từ một máy tính khác trong mạng LAN và chạy chương trình
từ shortcut này thì xuất hiện thông báo lỗi như sau:
If you click Continue, the application will ignore this error and attempt to
Continue. If you click Quit, the application will close immediately.
Tôi biết rằng lỗi trên là do chương trình có sử dụng cơ sở dữ liệu Access và
không biết cách khác phục như thế nào. Nhờ các chuyên gia về VB.NET
hướng dẫn tôi cài đặt chương trình như thế nào để mọi máy trong mạng
LAN đều có thể sử dụng chung chương trình được cài trên 1 máy.
Cấu hình mặc định của net framwork không cho phép chạy các net APP trên
network vì nó được cho là untrust, muốn các net APP triển khai được trên
các untrust location như maped network cần làm theo bước sau :
Vào settings - ... Control Panel... Administrative tools... Microsoft .NET
Framework Configuration... nhắp phải vào Runtime Security Policy...
chọn Adjust Security... rùi nhấn next... chỉnh Local Intranet sang "Full
Trust"... rùi NEXT... Vậy là ok........
Option Explicit
Private Declare Function GetLastError Lib "kernel32.dll" () As Long
' Exposed Enumeration
Public Enum mceItemStates
mceDisabled = 1
mceGrayed = 2
End Enum
psCaption = sCaption
End Property
Caption = psCaption
End Property
End Sub
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)
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 Long
Dim iHwnd As Long, iX As Long, iY 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
End Function
Option Explicit
lblLabel.BackColor = vbButtonFace
lblLabel.ForeColor = vbWindowText
End Sub
lblLabel.BackColor = vbHighlight
lblLabel.ForeColor = vbHighlightText
End Sub
oMenu.Add 7, oSubmenu3
End Select
End Sub
Return SystemInformation.BootMode.ToString
End Function
Public Function ComputerName() As String
'the computername
Return SystemInformation.ComputerName
End Function
Public Function DBCSEnabled() As Boolean
'returns true if system is capable of
'handling double-byte character set (DBCS) characters.
Return SystemInformation.DbcsEnabled
End Function
Public Function MenuFontName() As String
'operating system font name for menus
Return SystemInformation.MenuFont.FontFamily.Name
End Function
Public Function MenuFontSize() As Integer
'operating system font name for menus
Return SystemInformation.MenuFont.Size
End Function
Public Function MenuHeight() As Integer
'height of one menu line in pixel
Return SystemInformation.MenuHeight
End Function
End Function
Public Function PrimaryMonitorSize() As String
'Size of primary monitor
Return SystemInformation.PrimaryMonitorSize.ToString
End Function
Public Function Secure() As Boolean
'is security present on operating system
Return SystemInformation.Secure
End Function
Public Function UserDomainName() As String
'the domain name for the current user
Return SystemInformation.UserDomainName
End Function
Public Function UserInteractive() As Boolean
'is current process running in user-interactive mode.
Return SystemInformation.UserInteractive
End Function
Public Function UserName() As String
'user name
Return SystemInformation.UserName
End Function
Public Function WorkingArea() As String
Return SystemInformation.WorkingArea.ToString
End Function
End Class
SQL Data Provider VB.NET Class - The Class
The Class
This class is for simplifying and accelerating working with SQL, using this class is very simple;
there is a sample below for this class, which I hope is useful. You can report bugs, opinions
and suggestions to me.
Imports System
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Namespace SqlDataProvider
''' <summary>
''' This class provides a fast and universal method for accessing SQL Server
database.This class cannot be inherited.
''' </summary>
Public NotInheritable Class SqlDatabase
#End Region
''' <summary>
''' Initializes a new instance of the ADO.SqlDatabase class.
''' </summary>
''' <param name="connectionString">The connection used to open the SQL Server
database.</param>
Public Sub New(ByVal connectionString As String)
_connectionString = connectionString
End Sub
#End Region
''' <summary>
''' Gets or sets the string used to open a SQL Server database.
''' </summary>
''' <returns>The connection string that includes the source database name, and
other parameters needed to establish the initial connection.</returns>
Public Property ConnectionString() As String
Get
Return _connectionString
End Get
Set(ByVal value As String)
_connectionString = value
End Set
End Property
#End Region
#End Region
''' <summary>
''' Executes a Transact-SQL statement against the connection and returns the
number of rows affected.
''' </summary>
''' <param name="cmd">The Transact-SQL statement or stored procedure to execute
at the data source.</param>
''' <param name="cmdType">A value indicating how the
System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
''' <param name="parameters">The parameters of the Transact-SQL statement or
stored procedure.</param>
''' <returns>The number of rows affected.</returns>
Public Function ExecuteNonQuery(ByVal cmd As String, ByVal cmdType As
CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Integer
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim res As Integer = -1
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(cmd, connection)
command.CommandType = cmdType
Me.AssignParameters(command, parameters)
connection.Open()
transaction = connection.BeginTransaction()
command.Transaction = transaction
res = command.ExecuteNonQuery()
transaction.Commit()
Catch ex As Exception
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) AndAlso (connection.State =
ConnectionState.Open) Then connection.Close()
If Not (command Is Nothing) Then command.Dispose()
If Not (transaction Is Nothing) Then transaction.Dispose()
End Try
Return res
End Function
''' <summary>
''' Executes a Transact-SQL statement against the connection and returns the
number of rows affected.
''' </summary>
''' <param name="spname">The stored procedure to execute at the data
source.</param>
''' <param name="returnValue">The returned value from stored procedure.</param>
''' <param name="parameterValues">The parameter values of the stored
procedure.</param>
''' <returns>The number of rows affected.</returns>
Public Function ExecuteNonQuery(ByVal spname As String, ByRef returnValue As
Integer, ByVal ParamArray parameterValues() As Object) As Integer
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim res As Integer = -1
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
connection.Open()
SqlCommandBuilder.DeriveParameters(command)
Me.AssignParameters(command, parameterValues)
transaction = connection.BeginTransaction()
command.Transaction = transaction
res = command.ExecuteNonQuery()
returnValue = command.Parameters(0).Value
transaction.Commit()
Catch ex As Exception
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) AndAlso (connection.State =
ConnectionState.Open) Then connection.Close()
If Not (command Is Nothing) Then command.Dispose()
If Not (transaction Is Nothing) Then transaction.Dispose()
End Try
Return res
End Function
#End Region
''' <summary>
''' Executes the query, and returns the first column of the first row in the
result set returned by the query. Additional columns or rows are ignored.
''' </summary>
''' <param name="cmd">The Transact-SQL statement or stored procedure to execute
at the data source.</param>
''' <param name="cmdType">A value indicating how the
System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
''' <param name="parameters">The parameters of the Transact-SQL statement or
stored procedure.</param>
''' <returns>The first column of the first row in the result set, or a null
reference if the result set is empty.</returns>
Public Function ExecuteScalar(ByVal cmd As String, ByVal cmdType As CommandType,
Optional ByVal parameters() As SqlParameter = Nothing) As Object
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim res As Object = Nothing
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(cmd, connection)
command.CommandType = cmdType
Me.AssignParameters(command, parameters)
connection.Open()
transaction = connection.BeginTransaction()
command.Transaction = transaction
res = command.ExecuteScalar()
transaction.Commit()
Catch ex As Exception
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) AndAlso (connection.State =
ConnectionState.Open) Then connection.Close()
If Not (command Is Nothing) Then command.Dispose()
If Not (transaction Is Nothing) Then transaction.Dispose()
End Try
Return res
End Function
''' <summary>
''' Executes the query, and returns the first column of the first row in the
result set returned by the query. Additional columns or rows are ignored.
''' </summary>
''' <param name="spname">The stored procedure to execute at the data
source.</param>
''' <param name="returnValue">The returned value from stored procedure.</param>
''' <param name="parameterValues">The parameter values of the stored
procedure.</param>
''' <returns>The first column of the first row in the result set, or a null
reference if the result set is empty.</returns>
Public Function ExecuteScalar(ByVal spname As String, ByRef returnValue As
Integer, ByVal ParamArray parameterValues() As Object) As Object
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim res As Object = Nothing
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
connection.Open()
SqlCommandBuilder.DeriveParameters(command)
Me.AssignParameters(command, parameterValues)
transaction = connection.BeginTransaction()
command.Transaction = transaction
res = command.ExecuteScalar()
returnValue = command.Parameters(0).Value
transaction.Commit()
Catch ex As Exception
If Not (transaction Is Nothing) Then
transaction.Rollback()
End If
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) AndAlso (connection.State =
ConnectionState.Open) Then connection.Close()
If Not (command Is Nothing) Then command.Dispose()
If Not (transaction Is Nothing) Then transaction.Dispose()
End Try
Return res
End Function
#End Region
''' <summary>
''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the
System.Data.SqlClient.SqlCommand.Connection, and builds a
System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values.
''' </summary>
''' <param name="cmd">The Transact-SQL statement or stored procedure to execute
at the data source.</param>
''' <param name="cmdType">A value indicating how the
System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
''' <param name="parameters">The parameters of the Transact-SQL statement or
stored procedure.</param>
''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns>
Public Function ExecuteReader(ByVal cmd As String, ByVal cmdType As CommandType,
Optional ByVal parameters() As SqlParameter = Nothing) As IDataReader
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Dim res As SqlDataReader = Nothing
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(cmd, connection)
command.CommandType = cmdType
Me.AssignParameters(command, parameters)
connection.Open()
res = command.ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
End Try
Return CType(res, IDataReader)
End Function
''' <summary>
''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the
System.Data.SqlClient.SqlCommand.Connection, and builds a
System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values.
''' </summary>
''' <param name="spname">The stored procedure to execute at the data
source.</param>
''' <param name="returnValue">The returned value from stored procedure.</param>
''' <param name="parameterValues">The parameter values of the stored
procedure.</param>
''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns>
Public Function ExecuteReader(ByVal spname As String, ByRef returnValue As
Integer, ByVal ParamArray parameterValues() As Object) As IDataReader
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Dim res As SqlDataReader = Nothing
Try
connection = New SqlConnection(ConnectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
connection.Open()
SqlCommandBuilder.DeriveParameters(command)
Me.AssignParameters(command, parameterValues)
res = command.ExecuteReader(CommandBehavior.CloseConnection)
returnValue = command.Parameters(0).Value
Catch ex As Exception
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
End Try
Return CType(res, IDataReader)
End Function
#End Region
''' <summary>
''' Adds or refreshes rows in the System.Data.DataSet to match those in the data
source using the System.Data.DataSet name, and creates a System.Data.DataTable named
"Table."
''' </summary>
''' <param name="cmd">The Transact-SQL statement or stored procedure to execute
at the data source.</param>
''' <param name="cmdType">A value indicating how the
System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
''' <param name="parameters">The parameters of the Transact-SQL statement or
stored procedure.</param>
''' <returns>A System.Data.Dataset object.</returns>
Public Function FillDataset(ByVal cmd As String, ByVal cmdType As CommandType,
Optional ByVal parameters() As SqlParameter = Nothing) As DataSet
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Dim sqlda As SqlDataAdapter = Nothing
Dim res As New DataSet
Try
connection = New SqlConnection(_connectionString)
command = New SqlCommand(cmd, connection)
command.CommandType = cmdType
AssignParameters(command, parameters)
sqlda = New SqlDataAdapter(command)
sqlda.Fill(res)
Catch ex As Exception
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) Then connection.Dispose()
If Not (command Is Nothing) Then command.Dispose()
If Not (sqlda Is Nothing) Then sqlda.Dispose()
End Try
Return res
End Function
#End Region
#Region " ExecuteDataset "
''' <summary>
''' Calls the respective INSERT, UPDATE, or DELETE statements for each inserted,
updated, or deleted row in the System.Data.DataSet with the specified
System.Data.DataTable name.
''' </summary>
''' <param name="insertCmd">A command used to insert new records into the data
source.</param>
''' <param name="updateCmd">A command used to update records in the data
source.</param>
''' <param name="deleteCmd">A command for deleting records from the data
set.</param>
''' <param name="ds">The System.Data.DataSet to use to update the data source.
</param>
''' <param name="srcTable">The name of the source table to use for table
mapping.</param>
''' <returns>The number of rows successfully updated from the
System.Data.DataSet.</returns>
Public Function ExecuteDataset(ByVal insertCmd As SqlCommand, ByVal updateCmd As
SqlCommand, ByVal deleteCmd As SqlCommand, ByVal ds As DataSet, ByVal srcTable As String)
As Integer
Dim connection As SqlConnection = Nothing
Dim sqlda As SqlDataAdapter = Nothing
Dim res As Integer = 0
Try
connection = New SqlConnection(_connectionString)
sqlda = New SqlDataAdapter
If Not (insertCmd Is Nothing) Then insertCmd.Connection = connection :
sqlda.InsertCommand = insertCmd
If Not (updateCmd Is Nothing) Then updateCmd.Connection = connection :
sqlda.UpdateCommand = updateCmd
If Not (deleteCmd Is Nothing) Then deleteCmd.Connection = connection :
sqlda.DeleteCommand = deleteCmd
res = sqlda.Update(ds, srcTable)
Catch ex As Exception
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If Not (connection Is Nothing) Then connection.Dispose()
If Not (insertCmd Is Nothing) Then insertCmd.Dispose()
If Not (updateCmd Is Nothing) Then updateCmd.Dispose()
If Not (deleteCmd Is Nothing) Then deleteCmd.Dispose()
If Not (sqlda Is Nothing) Then sqlda.Dispose()
End Try
Return res
End Function
#End Region
''' <summary>
''' Executes a SQL query file against the connection.
''' </summary>
''' <param name="filename">SQL query file name.</param>
''' <param name="parameters">The parameters of the SQL query file.</param>
Public Sub ExecuteScript(ByVal filename As String, Optional ByVal parameters() As
SqlParameter = Nothing)
Dim fStream As FileStream = Nothing
Dim sReader As StreamReader = Nothing
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand = Nothing
Try
fStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
sReader = New StreamReader(fStream)
connection = New SqlConnection(ConnectionString)
command = connection.CreateCommand()
connection.Open()
While (Not sReader.EndOfStream)
Dim sb As New StringBuilder
While (Not sReader.EndOfStream)
Dim s As String = sReader.ReadLine
If (Not String.IsNullOrEmpty(s)) AndAlso (s.ToUpper.Trim = "GO")
Then
Exit While
End If
sb.AppendLine(s)
End While
command.CommandText = sb.ToString
command.CommandType = CommandType.Text
AssignParameters(command, parameters)
command.ExecuteNonQuery()
End While
Catch ex As Exception
Throw New SqlDatabaseException(ex.Message, ex.InnerException)
Finally
If (Not IsNothing(connection)) AndAlso (connection.State =
ConnectionState.Open) Then connection.Close()
If (Not IsNothing(command)) Then command.Dispose()
If (Not IsNothing(sReader)) Then sReader.Close()
If (Not IsNothing(fStream)) Then fStream.Close()
End Try
End Sub
#End Region
End Class
End Namespace
This class provides a fast and universal method for accessing SQL Server database.
Create Instance
ExecuteNonQuery Method
Executes a Transact-SQL statement against the connection and returns the number of
rows affected.
Dim params(0 To 1) As SqlParameter
params(0) = New SqlParameter("@Firstname", SqlDbType.NVarChar, 120)
params(0).Value = "Stefan"
params(1) = New SqlParameter("@Lastname", SqlDbType.NVarChar, 120)
params(1).Value = "Cameron"
sqldb.ExecuteNonQuery("Insert Into dbo.Users(Firstname, LastName)
Values(@FirstName, @LastName)", CommandType.Text, params)
If you are using stored procedure,you can execute that without declaring parameters
such as following code:
sqldb.ExecuteNonQuery("dbo.CreateUser", Nothing, "Stefan", "Cameron")
ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned
by the query. Additional columns or rows are ignored.
Dim count As Integer = sqldb.ExecuteScalar("Select Count(*) From
dbo.Users", CommandType.Text)
MsgBox("Number of row(s): " & count)
ExecuteReader Method
If you are using stored procedure,you can get the value of 'return value parameter'.
Create Procedure dbo.UserExists
(
@Firstname nvarchar(120),
@Lastname nvarchar(120)
)
As
Begin
If Exists(Select * From dbo.Users Where (Firstname = @Firstname)
And (Lastname = @Lastname))
Return 1
End
FillDataset Method
Adds or refreshes rows in the System.Data.DataSet to match those in the data source
using the System.Data.DataSet name, and creates a System.Data.DataTable named
"Table."
ExecuteDataset Method
Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated,
or deleted row in the System.Data.DataSet with the specified System.Data.DataTable
name.
' Getting the System.Data.DataSet.
Dim ds As DataSet = CType(DataGridView1.DataSource, DataTable).DataSet
If you want to skip the chitchat: the .NET code example is at the end of this post
First the symantics: when we create a new form, this form has a name. If we refer to that
name, we actually refer to the name of the type of object that is just created.
When to use
Of course when reading the subject you might think: why not just pass the form to a
parameter that takes a form (or control/object)?
The answer is: you don't when it is not sure, when or if a new instance of the object has to be
created or, as mentioned, when the procedure is called it is not known which class has to be
created.
You could of course hold a bunch of created objects, but that would be a shameless misuse of
memory.
Imagine the following scenario (seen something like this in a post, but can't find it anymore):
You have a class that is able to trap an event, say the doubleclick of a textbox, and has to
open a form when it occurs. If it's always the same form, that's easy, but what if you want it
to be determined during runtime? This is a quite common story: doubleclick on article opens
the detail form of that article, doubleclick on supllier opens that particular form. If you use a
form variable, how do you say to the class which form should be opened? This will not work
Code:
Dim FormToOpen as Form 'you don't want to open it right away, you want to know when the
time comes what form to open
FormToOpen = Form1
You could say FormToOpen = new Form1, but then 1. an instance would be immediately
created, even if it never will be used: memory leak. 2. you can never close the form, you'll
always have to use the same instance created when setting the form. Consequently, you can
never open more than 1 instance using this way.
The solution: use the type. If you know the type, the Activator class will enable you to open
(and return) an instance of that form at any time and as much times as you like. (The
Activotor class exposes the function CreateInstance which returns an instance of the specified
object)
The following code creates an instance of the type form1 and shows it.
Code:
CType(Activator.CreateInstance(GetType(Form1)), Form).Show()
Or for better readability, the same code split up:
Code:
Code:
'VB6
Dim FormName as String
How To Print a Form
http://vbcity.com/forums/faq.asp?tid=28614
Difficulty Level : Intermediate
This is how you can take a picture of the form and print it.
First thing you have to do is add a PrintDocument component to the form. You can get that
from the Toolbox (way down the list).
Then you need to add a PrintDialog to the form as well. Also a button that says "Print" is
probably a good idea...
Code:
'We declare this here, cause were going to take the picture befor we show the print dialog
'I tried to take the picture in the PrintPage sub but it didnt work, would print the dialogs, etc.
'So we take the picture when the user presses the button, then show the dialog.
Private Print_Image As Image
'Clean Up
FormG.ReleaseHdc(HDC1)
memG.ReleaseHdc(HDC2)
Muon' xem moi. nguoi` dung` mo hin`h layer nhu* the' nao` , chi tiet' ^^ .
Kernel
DataAccess
Bussiness
User Control
Presentation
cac' lop' nay` la` cac' lop' chi? nhan. cac' tham so' , va` duoc. cac' lop' phia' sau ke' thua` .
Common la` lop' chua cac' ham` static dung` chung
getConnection() tra? ve` connection
readConnfig(configName) doc config trong file config
encrypt()
decrypt()
...
AppException la` lop' ke' thua` tu` Exception , moi. Exception trong ung' dung. se~ duoc. throw new
cai' nay` , roi` se~ bat' het' tai. ham` main , tham so' truyen` vao` la` Message , InnerException .
SqlBase la` lop' quan? ly' Sql chung nhat' , input la` 1 connection , se~ co' cac' ham` connect ,
disconnect, ExcuteNonReturn , FillDataSet , ,,,etc , dung` voi' connection la` Sql
OdbcBase tuong tu.
XmlBase la` lop' quan ly' Xml chung , co' cac' method Creat, Remove , Update , Read cac Key va`
Value .
Tang` DataAccess se~ viet' cac' lop' quan ly' vao` ra du~ lieu. , ke' thua` tu` SqlBase , or OdbcBase
... , moi~ mot. doi' tuong. se~ co' 1 lop' tai. day , vi' du. Student , Manager ,...etc . cac' cau lenh. Sql
duoc. viet' tai. lop' nay` , va` su? dung. cac' ham` tu` lop' SqlBase de? excute .
Bussiness la` tang` tiep' theo , voi' moi~ doi' tuong. cua? DataAccess , se~ co' 1 lop' tai. Bussiness
de? control , lop' nay` se~ new 1 lop' tuong ung' tai. DataAccess de? su? dung. , du~ lieu. truyen`
vao` la` ca'c bien' duoc. validate , roi` truyen` xuong' cho DataAccess de? thanh` cau lenh. Sql ,
User Control la` tang` khoi? tao. cac' Modules , No' nhan. cac' du~ lieu. tu` Bussiness chuyen? len ,
va` fill vao` cac' Control . Moi~ module se~ su? dung. 1 so' luong. gioi' han. cac' control , vi' du.
modules view Student , se~ su? dung 1 listbox , 3 textBox ... gi` gi` do' , cai' user Control nay` ko
can` biet' textBox la` gi` , cu' fill vao` thoi , moi~ lop' tai. tang` UserControl la` 1 module trong
chuong trin`h . va` duoc. ke' thua` tu` lop' moduleBase tu` kernel ,
Vi' du. ung' dung. cua? em la` tao. Report quan? ly' Examination , thi` ko can` biet' giao dien. trong
ra sao , duoi' kernel se~ co' 1 interface , khai bao' cac' control can` co' , va` cai' user control se~
theo do' ma` fill vao` .
Tang` tren cung` hoan toan` chi? la` giao dien. , tuan theo cai' interface kia ,
Cac'h thiet' ke' phia' tren cua? em co' cai' loi. , do' la` em co' the? lam` da giao dien. 1 cach' de~
dang` , moi. thu' van~ hoat. dong. , mac. du` ko can` den' tang` tren cung` , tang` tren cung` chi?
de? hien? thi. ma` thoi , vi` the' co' the? de~ dang` chuyen? thanh` giao dien. dong` lenh. voi' cac'
ung' dung. unix
. Chia viec. cho cac' coder cung~ de~ dang` , voi' moi~ modules phan ra , nguoi` code se~ viet' 2
lop' , 1 lop' tai. DataAccess de? chay. lenh. , 1 lop' tai. Bussiness de? validate du~ lieu. .
Tang` kernel va` usercontrol hoan` toan` dung` lai. duoc. .
Co' the? thuc. hien. multi connection .
( trong cac' ung' dung. chuyen? doi? database tu` Access --> Sql server , rat pho? bien' tai. VN )
Voi' moi~ nguoi` viet' phan` cua? mi`nh , se~ ko biet' tang` tren co' cai' gi` , chi? duoc. dua cho 1
cai' dll duoc. bien dich tu` trang` tren. Co' the? bao? mat. thong tin ve` he. thong' .
Mong moi. nguoi` gop' y' ve` cac'h thiet' ke' cua? em ^^ .
code đệ quy duyệt toàn bộ các menu trong 1 MENUTRIP ( bất kể có bao nhiêu cấp ), bạn có thể
sửa đổi đoạn code này để tạo TREE trong tree view hay GRID , tham số DT là 1 datatable chứa
các menu mà người dùng được phép truy cập, nếu không tìm thấy thì menu đó sẽ bị disable
Đoạn mã của mình là dùng đệ quy để duyet toàn bô các item trong menu dùng để :
- Vẽ cây phân quyền ( tree view hoặc dùng c1 flexgrid )
- Duyet menu để phân quyen - thường là ẩn menu đó đi
sửa đổi 1 chút cho khớp với dữ liệu của bạn .
Chỉ áp dụng cho menutrip
Tôi cần hiển thị danh sách các đơn hàng và chi tiết từng đơn hàng trên 1 grid. có bảng
tblDonHang và tblChiTietDonHang. Thường khi lập trình ta sẽ tạo ra dataset có 2 bảng đó và đặt
quan hệ Master - Detail thì việc hiện thị là dễ dàng. Dự án được xây dựng theo phương pháp
hướng đối tượng --> có 2 lớp tương ứng là clsDonHang và clsChiTietDonHang. 2 lớp trên có các
phương thức trả về dữ liệu là tập các object chứ không còn là các record nên tôi chưa có cách.
Bác nào đã xử lý vấn đề này thì có thể giúp tôi xử lý với! help me!!!!!!!
Thông thường nếu xây dựng các lớp xử lý dữ liệu sẽ có các phương thức trả về đối tượng mang
dữ liệu tương ứng.
Ví dụ trong trường hợp của bạn, tôi giả sử mỗi đối tượng TABLE ( đơn hàng, chi tiết đơn hàng)
đều có các phương thức sau:
FillData: lấy dữ liệu và điền dữ liệu vào đối tượng bạn cung cấp.
GetData: lấy dữ liệu và trả về đối tượng tương ứng chứa dữ liệu đó.
Có thể phương thức này có dạng sau (trong trường hợp của bạn):
public class ChiTietDonHangDataTable : System.Data.Table
{
}
public class DonHangDataTable : System.Data.Table
{
}
public class clsDonHang
{
public void FillData (DonHangDataTable donhang)
{
}
public DonHangDataTable GetData ()
{
DonHangDataTable _donhang = new DonHangDataTable();
//lấy dữ liệu ở đây
// ....................
return _donhang;
}
}
public class clsChiTietDonHang
{
public void FillData(DonHangDataTable donhang)
{
}
public DonHangDataTable GetData()
{
DonHangDataTable _donhang = new DonHangDataTable();
//lấy dữ liệu ở đây
// ....................
return _donhang;
}
}
//Vậy trong trường hợp của bạn có thể xử lý như sau:
public void InitDataSet()
{
_objDonHang.FillData(_dtDonHang);
_objChiTietDonHang.FillData(_objChiTietDonHang);
_dsDonHang.Tables.Add(_dtDonHang);
_dsDonHang.Tables.Add(_dtChiTietDonHang);
Có lẽ tôi chưa hiểu rõ ý bạn muốn trao đổi, nhưng theo như tôi hiểu là bạn muốn sử dụng các
object đó với các giá trị của các property của nó lên các control, vấn đề này thì tôi thấy NET 2 đã
xử lý rồi mà, bạn chứa các object đó trong một List<>, sau đó bạn chỉ việc dùng list này
làm datasource này cho các control có khác gì là datatable, dataview hay datareader đâu, ngoài
ra để binding theo đúng nghĩa bạn còn có thể xây dựng các phương thức để insert, update và
delete nữa, nó còn có vẻ tiện hơn là sử dụng các command cho cái adapter trước kia. Thực ra
sau khi dùng cái này tôi ít khi còn sử dụng datatable, dataview ... để tương tác dữ liệu đằng UI
nữa.
Hitting the enter key in a TextBox can sometimes have undesired effects like the
wrong submit Button being “clicked“. The method described below allows you to
specify a default Button to submit when the user hits the enter key in a TextBox.
When you press a key on your keyboard, the js OnKeyPress event is fired. This calls
a function to which we pass the id of the button associated with the TextBox. The
function gets a reference to the button and simuilates a mouse-click on the Button.
We perform a browser detection because IE and Netscape have different event
models. The function finally returns false so that the keypress event is cancelled
(otherwise a second form submit will be raised). This works with newer versions of
IE/Netscape.
//code behind
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" +
Button1.ClientID + "')");
This causes web control Button1 to be clicked when the enter key is hit inside
TextBox1.
i am taking one textBox and DataGrid. i want to fill DataGrid while typing the letter
(KeyPress-Event).the coding is as follows
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Dim Ds As DataSet
Dim Da As SqlDataAdapter
Ds = New DataSet
Da = New SqlDataAdapter(com)
Da.Fill(Ds, "EMPLOYEE")
DataGrid1.DataSource = Ds
DataGrid1.DataBind()
con.Close()
End Sub
Mnh có một form với nhiều textbox nhập liệu. Để di chuyển giữa các text box thì mình đặt
tabindex theo thứ tự, khi form hoạt động thì nhấn tab để di chuyển. Nhưng mình muốn người
dùng khi nhấn vào phím mũi tên trên bàn phím thì cũng có tác dụng như phím tab. Vậy sự kiện
bắt phím này như thế nào.
Mình thấy vb.net có hỗ trợ e.keycode, e.keydata, e.keyvalues mình ko biết cách dùng 3 cái này
thì khác gì nhau. Mình thấy cái e.keycode, e.keydata hình như giống nhau
Vấn đề 2:
Mình có một maskedtextbox để nhập liệu ngày tháng vào hiển thị dữ liệu lên datagrid. Sau
đó mình muốn dữ liệu sẽ hiện lại lên maskedtextbox khi duyệt dữ liệu. Nhưng với ngày tháng vd
05/02/2003 thì khi hiện lên maskedtextbox với hàm định dạng Ctype(object, datetime) thì nó hiện
lên là 52/20/07__
Vậy phải định dạng thế nào để có thể hiển thị số 0 trước ngày tháng <10 để cho đúng
dạng mm
O van de 1:
Ban mo MSDN len tra tu SendKey.
Vấn đề 2:
drg.Cell[xyz].ToString("dd/MM/yyyy");
Resize Control khi thay đổi độ phân giải của màn hình
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim rec As Rectangle
Dim CtlOut, CtlIn As Control
For Each CtlOut In Me.Controls
CtlOut.Tag = CtlOut.Top / Me.Height & ";" & CtlOut.Left / Me.Width & ";" &
CtlOut.Width / Me.Width & ";" & CtlOut.Height / Me.Height & ";" & CtlOut.Font.Size /
Me.Height
If TypeOf CtlOut Is GroupBox Then
For Each CtlIn In CtlOut.Controls
CtlIn.Tag = CtlIn.Top / CtlOut.Height & ";" & CtlIn.Left / CtlOut.Width & ";" &
CtlIn.Width / CtlOut.Width & ";" & CtlIn.Height / CtlOut.Height & ";" & CtlIn.Font.Size
/ CtlOut.Height
Next
End If
Next
Me.Height = Screen.GetBounds(rec).Height
Me.Width = Screen.GetBounds(rec).Width
Me.Top = 0 : Me.Left = 0
End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Resize
Dim CtlOut, CtlIn As Control
For Each CtlOut In Me.Controls
ResizeControl(Me, CtlOut)
If TypeOf CtlOut Is GroupBox Then
For Each CtlIn In CtlOut.Controls
ResizeControl(CtlOut, CtlIn)
Next
End If
Next
End Sub
Private Sub ResizeControl(ByVal PaCtl As Object, ByVal ChCtl As Control)
Dim ctlTag, CtlTop, CtlLeft, CtlWidth, CtlHeight, ctlFontSize As String
Dim P1, P2 As Integer
ctlTag = ChCtl.Tag.ToString
P1 = ctlTag.IndexOf(";")
CtlTop = ctlTag.Substring(0, P1)
P2 = P1 + 1
P1 = ctlTag.IndexOf(";", P2)
CtlLeft = ctlTag.Substring(P2, P1 - P2)
P2 = P1 + 1
P1 = ctlTag.IndexOf(";", P2)
CtlWidth = ctlTag.Substring(P2, P1 - P2)
P2 = P1 + 1
P1 = ctlTag.IndexOf(";", P2)
CtlHeight = ctlTag.Substring(P2, P1 - P2)
P2 = P1 + 1
ctlFontSize = ctlTag.Substring(P2)
ChCtl.Top = PaCtl.Height * CtlTop
ChCtl.Left = PaCtl.Width * CtlLeft
ChCtl.Height = PaCtl.Height * CtlHeight
ChCtl.Width = PaCtl.Width * CtlWidth
ChCtl.Font = New Font(ChCtl.Font.Name, CSng(PaCtl.Height * ctlFontSize),
ChCtl.Font.Style)
End Sub
End Class
-----
Sub AutoSize(ByVal Form1 As Variant)
On Error Resume Next
If Screen.Width <> 12000 And Screen.Height <> 9000 Then
Dim i As Long, Dai As Single, Rong As Single
Dai = Screen.Width
Rong = Screen.Height
Form1.Width = Form1.Width / (12000 / Dai)
Form1.Height = Form1.Height / (9000 / Rong)
For i = 0 To Form1.Controls.Count - 1
Form1.Controls(i).Top = Form1.Controls(i).Top / (12000 / Dai)
Form1.Controls(i).Left = Form1.Controls(i).Left / (9000 / Rong)
Form1.Controls(i).Width = Form1.Controls(i).Width / (12000 / Dai)
Form1.Controls(i).Height = Form1.Controls(i).Height / (9000 / Rong)
Form1.Controls(i).AutoSize = True
Next i
End If
Err.Clear
End Sub
' Ban co the thay 2 so : 12000 va 9000 bang cac gia tri khac tuong ung voi do phan giai chuan
cua ban la 1024 x 800
Tạo form không thể duy chuyển được
Bạn muốn tạo một form chiếm giữ một vị trí cố định trên màn hình và không thể di
chuyển được.
Tạo một form không-đường-viền bằng cách thiết lập thuộc tính FormBorderStyle là
None. Hoặc bạn có thể hiện thực thuộc tính Moveable cho form.
Bạn có thể tạo một form không-đường-viền bằng cách thiết lập thuộc tính
FormBorderStyle là None. Các form thế này không thể di chuyển được. Và chúng nếu
muốn có đường viền, bạn phải viết mã lệnh vẽ hoặccũng thiếu mất đường viền sử dụng
hình nền.
Có một cách khác để tạo một form không thể di chuyển được và form này có đường viền
giống điều kiểm. Trước tiên, thiết lập các thuộc tính ControlBox, MinimizeBox, và
MaximizeBox là False. Kế tiếp, thiết lập thuộc tính Text là chuỗi trống. Khi đó, form sẽ
có đường viền nổi màu xám hoặc đường kẻ màu đen (tùy thuộc vào tùy chọn
FormBorderStyle mà bạn sử dụng), tương tự như Button.
Phần dưới đây sẽ trình bày một cách tiếp cận khác: hiện thực thuộc tính Moveable cho
form (trong Visual Basic 6, form có thuộc tính Moveable, nhưng trong .NET, thuộc tính
này không còn nữa). Trước tiên, chúng ta xây dựng lớp ImmoveableForm như sau (thừa
kế từ [vb]System.Windows.Forms.Form):
<System.ComponentModel.Category("Behavior"), _
System.ComponentModel.Description("Allows the form to be moved")> _
Public Overridable Property Moveable() As Boolean
Get
Return bMoveable
End Get
Set(ByVal Value As Boolean)
If bMoveable <> Value Then
bMoveable = Value
End If
End Set
End Property
End Class[/vb]
Để sử dụng lớp trên, bạn cần hiệu chỉnh phần mã do Visual Studio kết sinh cho form của
bạn như sau (phần in đậm):
Trích từ "Các giải pháp lập trình VISUAL BASIC .NET (tập 1)"
http://www.dvpub.com.vn/dv/details.aspx?itemid=244
Cách để xác minh mã số sách có hợp lệ hay không trong VB.Net
Xác nhận tính hợp lệ của ISBN
Bạn muốn xác minh một ISBN (International Standard Book Number: mã số sách chuẩn
quốc tế) có hợp lệ hay không.
Tính và kiểm tra bằng phép Mod 11.
Trong trường hợp này, bạn nhân mỗi chữ số với vị trí của nó (ngoại trừ số cuối cùng),
cộng những số này với nhau, và kiểm tra phần dư của tổng chia cho 11 có trùng với chữ
số cuối cùng hay không.
Dưới đây là hàm mà bạn có thể sử dụng để kiểm tra ISBN:
[vb]Private Function ValidateISBN(ByVal value As String) As Boolean
Dim CheckSum As Integer = 0
Dim i As Integer
For i = 0 To value.Length - 2
CheckSum += Integer.Parse(value.Chars(i)) * (i + 1)
Next
Dim CheckDigit As Integer
CheckDigit = Integer.Parse(value.Chars(value.Length - 1))
Return (CheckSum Mod 11 = CheckDigit)
End Function[/vb]
Bạn có thể thử nghiệm hàm này như sau:
[vb]If ValidateISBN("1861007353") Then
' Đây là ISBN hợp lệ.
End If[/vb]
Nhớ rằng phương thức này giả sử mọi dấu “-” đã bị loại khỏi chuỗi. Nếu không chắc
bước này đã được thực hiện hay chưa, bạn có thể viết thêm mã để loại bỏ hoặc bỏ qua
dấu “-” .
Trích từ "Các giải pháp lập trình Visual Basic .Net (tập 1)"
http://www.dvpub.com.vn/dv/details.aspx?itemid=244
Mã hóa password
Tôi muốn mã hóa password trước khi chèn vào DB, không biêt bạn nào đã từng làm
có thể giúp tôi trong code VB.NET được không?
Bạn có thể dùng code sau:
Code:
Private Function Mahoa(ByVal pass As String) As String
Dim uEncode As New UnicodeEncoding
Dim result As Byte() = uEncode.GetBytes(pass)
Dim md5 As New MD5CryptoServiceProvider
result = md5.ComputeHash(result)
Return Convert.ToBase64String(result)
End Function
Và import thêm cái này là ok: System.Security.Cryptography
Đối số trong sự kiện VB.NET
Trong bài này tôi xin nói về hai đối số mà có mặt trong mọi sự kiện của VB.Net. Một
đối số gửi thông tin về đối tượng và một đối số gửi thông tin về hành động mà gây ra
sự kiện.
Hai đối số đó là sender và e. Đây là khai báo của sự kiện Click cho một nút:
[HIGHLIGHT="vb"]Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
'
End Sub[/highlight]
Đối số sender lưu thông tin về đối tượng mà gây ra sự kiện, chúng ta sử dụng đối số
này để xác định kiểu của đối tượng mà sinh ra sự kiện. Ví dụ:
[HIGHLIGHT="vb"]Console.WriteLine(sender.ToString)
System.Windows.Forms.Button, Text: Button1Console.WriteLine(sender.GetType)
System.Windows.Forms.Button[/highlight]
Đối số thứ hai e chứa mọi thông tin mà bạn cần để xử lý sự kiện. Đối tượng e có một
vài thuộc tính mà phụ thuộc vào kiểu của sự kiện và điều khiển sinh ra sự kiện.
Thông tin mà bạn cần thiết để xử lý các kiểu sự kiện được truyền qua đối này.
Sự kiện chuột:
Dãy các sự kiện chuột xảy ra khi bạn nhấn chuột, thứ tự của chúng lần lượt là
MouseDown, Click và MouseUp. Sự kiện chuột xảy ra ngay cả khi bạn di chuyển
chuột qua các điều khiển: sự kiện MouseEnter xảy ra khi chuột bắt đầu đi vào điều
khiển, dãy các sự kiện MouseMove xảy ra khi di chuột trên điều khiển, sau đó là sự
kiện MouseHover và MouseLeave xảy ra khi chuột rời khỏi điều khiển. Mặc dù các sự
kiện khác nhau nhưng chúng cùng gửi thông tin cho ứng dụng qua đối e và bạn có
thể khai thác vài thuộc tính của đối e này để sử dụng trong chương trình của mình:
Button: trả lại một hằng tượng trưng cho nút được nhấn, và nhận giá trị thuộc tập
hằng kiểu liệt kê MouseButtons: Left, Middle, None, Right, XButton1, và XButton2.
Hai giá trị cuối cùng dùng cho kiểu chuột năm nút và tương ứng với hai nút ở hai bên
cạnh. Tuy nhiên đối e trong sự kiện Click hoặc DblClick không cung cấp thuộc tính
Button vì hai sự kiện này chỉ được thực hiện với nút chuột trái.
Clicks: trả về số lần chuột được nhấn và thả, chỉ nhận giá trị 1 hoặc 2.
Delta: thuộc tính được dùng với chuột có nút cuộn, trả về số lần nút cuộn được quay.
Bạn có thể dùng thuộc tính này để biết hộp Textbox đã được cuộn như thế nào.
X,Y: trả lại toạ độ của chuột lúc chuột được nhấn hoặc được thả. Toạ độ chuột được
tính theo toạ độ tương đối của điều khiển liên quan theo pixel. Nếu bạn nhận chuột ở
góc trái trên của một nút thì toạ độ trả về sẽ là 0,0.
Sự kiện bàn phím:
Các điều khiển mà nhận các text thường có nhiều sự kiện bàn phím, ví dụ như điều
khiển TextBox. Sự kiện KeyPress xảy ra khi một phím được nhấn còn sự kiện
KeyDown và KeyUp xảy ra khi một phím được nhấn và thả tương ứng. Sau đây là
khai báo của sự kiện KeyDown của TextBox
[HIGHLIGHT="vb"]Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e
As_ System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
End Sub[/highlight]
Đối thứ hai cung cấp thông tin về trạng thái bàn phím và phím được nhấn thông qua
các thuộc tính của nó.
Alt, Control, Shift: ba thuộc tính trả về giá trị True/False xác định phím điều khiển
tương ứng được nhấn khi phím được nhấn.
KeyCode: trả về mã phím được nhấn và là một giá trị thuộc tập hằng liệt kê Keys.
Tập hằng này chứa giá trị cho mọi phím, ví dụ kí tự "a" và "A" đều có mã là KeysA,
mã của phím "0" bên keypad là Key0, phím F1 là KeyF1. Vài phím điều khiển như
NumLock, ScrollLock, WakeUp và Sleep... luôn trả về KeyCode bằng 0
KeyData: trả về giá trị long xác định phím được nhấn, nó cũng tương tự như thuộc
tính KeyCode nhưng phân biệt kí tự và kí hiệu trên phím.
KeyValue: trả lại giá trị cho phím được nhấn, thường thì cùng giá trị như KeyData, chỉ
khác biệt ở các phím điều khiển.
--------------
Translate from Mastering VB.NET
Thêm, sửa trùng mã
Em muốn hỏi khi thêm dữ liệu ở bảng có khoá chính có kiểu nchar
thì khi thêm hay sửa dữ liệu có thể dẫn đến trùng mã
gây lỗi
Trong trường hợp này Em nên sử dụng thêm một mã nữa.Mã này chính là mã sẽ thay đổi
do người dùng nhập.Và trong thủ tục SQL Em viết như sau:
Để đưa dữ liệu từ bảng khác lên Combo Em làm như sau nhé
Đầu tiên Em viết một thủ tục bằng SQL 2000 để lấy ra bảng Em cần đưa lên Combo
.Chẳng hạn bảng Branch
AS
'*********************************************************
'Ham dua du lieu vao combo
Public Shared Sub GetData_Into_Cbo(ByVal sqlstr As String, ByVal cboName As
ComboBox, ByVal cboValue As String, ByVal cboDisplay As String, ByVal IsNull As
Boolean,ByVal objConn As SqlConnection)
Try
'ket noi CSDL de lay ra dataset
Dim datAdapter As SqlDataAdapter = New SqlDataAdapter
Dim datDsCB As DataSet = New DataSet
datAdapter = ReturnDataAdapter(sqlstr,objConn )
datAdapter.Fill(datDsCB)
datAdapter.Dispose()
'Kiem tra co null hay khong
If IsNull Then 'Neu isnull=true
' dinh nghia bien cot va dong
Dim datTable As DataTable
Dim i As Byte
Dim myDataColumn As DataColumn
Dim myDataRow As DataRow
' tao dong cot bang
datTable = New DataTable
myDataColumn = New DataColumn
myDataColumn.DataType = Type.GetType("System.String")
myDataColumn.ColumnName = cboDisplay
'dua cot vao bang
datTable.Columns.Add(myDataColumn)
'cot thu 1
myDataColumn = New DataColumn
myDataColumn.DataType = Type.GetType("System.String")
myDataColumn.ColumnName = cboValue
'dua cot vao bang
datTable.Columns.Add(myDataColumn)
'them mot dong
myDataRow = datTable.NewRow
myDataRow(cboValue) = ""
myDataRow(cboDisplay) = ""
'dua dong vao bang
datTable.Rows.Add(myDataRow)
If datDsCB.Tables(0).Rows.Count > 0 Then
For i = 0 To datDsCB.Tables(0).Rows.Count - 1
myDataRow = datTable.NewRow
myDataRow(cboValue) = datDsCB.Tables(0).Rows(i).Item(cboValue)
myDataRow(cboDisplay) = datDsCB.Tables(0).Rows(i).Item(cboDisplay)
'dua dong vao bang
datTable.Rows.Add(myDataRow)
Next
End If
'Dua bang vao Dataset
datDsCB.Tables.Add(datTable)
'gan gia tri nguon cho Combo
cboName.DataSource = datDsCB.Tables(datTable.TableName)
Else 'Neu khong null
'gan gia tri nguon cho Combo
cboName.DataSource = datDsCB.Tables(0)
End If
'cot dua vao gia tri nho cua combo
cboName.ValueMember = Trim(cboValue)
' dua dl tu cot de hien thi tren combo
cboName.DisplayMember = Trim(cboDisplay)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
GetData_Into_Cbo("SP_Select_Branch",cboBranch,"BranchID","BranchName",False,Co
nn)
Trong đó : SP_Select_Branch là tên thủ tục Em viết trong SQL,cboBranch là tên
Combo,Conn là đối tượng kết nối
Bạn đã tạo được giao diện XP trong VB.NET 2003 chưa? Chắc là chưa đúng không?
Nếu chưa tạo được bạn hãy làm theo các bước sau đây đảm bảo sẽ có giao diện XP
Sau khi bạn kéo và thả các đối tượng vào Form bạn vào Properties tiếp đến bạn chọn
thuộc tính FlatStyle là System (Tất nhiên sẽ có một số đối tượng không có thuộc tính này
ví dụ như ComboBox chẳng hạn ,nhưng mình không cần quan tâm nó sẽ tự động nhận)
Sau đó bạn tải File XP.EXE.manifest rồi đổi tên XP thành tên dự án của bạn và vất vào
thư mục chứa File .EXE là xong.
Cụ thể là : Giả sử dự án của bạn tên là KT (KT là tên hiện trong Exploer Solution) bạn
sẽ đổi như sau
Đổi XP.EXE.manifest thành KT.EXE.manifest rồi vất vào thư mục chứa .EXE.
Thay oi tai sao moi lan em cap nhat du lieu thi tren C1flexgrid ko tu dong cap nhat a. Em
co viet cau lenh: tenluoi.refesh() nhung cung ko nhan. Co can phai viet them doan lenh
nao ko a?
Em chỉ cần gọi lại phương thức (thủ tục) GetDataGird() sau khi cập nhận dữ liệu thành
công là xong
GetDataGird() nằm trong sự kiện khi click chuột vào nút Cập nhật Em a.
Trong VB.NET việc đưa dữ liệu ra DataSet thì quả là đơn giản đúng không ?.Những liệu
bạn đã biết lọc hoặc truy vấn dữ liệu trong DataSet để lấy ra những thông tin cần thiết
chưa?.Điều này thì chắc không phải ai cũng biết.
Tối lấy một trường hợp thế này.Giả sử tôi có một DataSet chứa dữ liệu của bảng
KhachHang với các trường MaKH,TenKH
Bây giờ tôi muốn lấy ra những khách hàng có mã >10 .Đây chính là truy vấn dữ liệu
trong DataSet
Tôi xin giới thiệu với chúng ta một cách làm như sau:
Để lấy giá trị thứ i trong RowMaKH bạn chỉ cần dùng câu lệnh
RowMaKH(i).Item("MaKH")
cach nao de co combobox tren luoi flexgrid
Có hai trường hợp xảy ra.
Một do người dùng định nghĩa và tạo thành ComboBox. Giả sử Thầy muốn tạo ra
combobox có nam và nữ.Trường hợp này ta làm như sau:
'*****************************************************
'ham truyen gia tri vao cac Sortedlist de dua vao cac cbo cua luoi
Public Shared Function Add_Data_Grid(ByVal strSqlStore As String, ByVal sKey As
String, ByVal sValue As String) As SortedList
Dim datSqlAdapter As SqlDataAdapter
Dim i As Integer
Dim datDs As DataSet
'khoi tao mot SorttedList
Dim slist As SortedList = New SortedList
Try
slist = New SortedList
datSqlAdapter = New SqlDataAdapter
datDs = New DataSet
datSqlAdapter = ReturnDataAdapter(strSqlStore)
datSqlAdapter.Fill(datDs, "cboTable")
datSqlAdapter.Dispose()
If datDs.Tables("cboTable").Rows.Count > 0 Then
For i = 0 To datDs.Tables("cboTable").Rows.Count - 1
slist.Add(Trim(datDs.Tables("cboTable").Rows(i).Item(sKey).ToString),
Trim(datDs.Tables("cboTable").Rows(i).Item(sValue)))
Next
End If
datDs.Dispose()
Return slist
Catch ex As Exception
MsgBox(ex.ToString)
datDs.Dispose()
End Try
End Function
Các đoạn này sẽ được đặt sau GetDataGird() và trong FormatGird() Em thêm câu lệnh
GirdName.AllowEditing=True
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
Thứ nhất : Đối với dữ liệu ngày, tháng Em không nên dùng đối tượng TextBox mà nên
dùng đối tượng DateTImePicker .Mặc định sẽ có dữ liệu ngày tháng, Nếu cố tình không
nhập thì vẫn có.Còn nếu Em dùng TextBox thì chỉ cần kiểm tra . If TextBox.Text=""
then MessageBox.Show("Bạn chưa nhập ngày sinh")
Thứ 2. Để kiểm soát được vấn đề khoá ngoại và khoá chính như vậy thì rất đơn giản Em
làm như sau nhé
Em xem trường khoá ngoại đó có cho phép Null hay không.Nếu cho phép Null thì không
cần quan tâm đến trường khoá chính có dữ liệu hay không.Còn nếu không cho phép Null
thì khi Em dưa dữ liệu từ bảng có khóa chính lên Combo để chọn thì Em mặc định cho
Combo có dữ liệu là xong.Kể cả khi người dùng không chọn thì mặc định vẫn có dữ liệu .
lam the nao de co checkbox hien len tren luoi
Tuỳ thuộc vào cột nào Em cần có CheckBox thì Em sẽ cho làm CheckBox và chỉ cần
dùng thuộc tính .DataType
GrdName.Cols("GioiTinh").DataType=GetType(Boolean)
GrdName.Cols("GioiTinh").AllowEditing=True
Tuỳ thuộc vào cột nào Em muốn cho là ngày tháng mà viết code tương ứng và dùng
thuộc tính .DataType.
Ví dụ Em muốn cột ngày sinh (NgaySing) là ngày tháng.Em làm như sau
GrdName.Cols("NgaySinh").DataType=GetType(DataTime)
GrdName.Cols("NgaySinh").AllowEditing=True
GrdName : Là tên lưới
NgaySinh : Là cột ngày sinh sẽ hiện trên lưới
Để làm được điều này thì trong thủ tục sp_Insert_Update_mFaculty Em thêm một tham
số @KT như sau
sp_Insert_Update_mFaculty
@ma int,
........
@KT bit output
AS
Param(0).Value=....
....
Param(5).Direction=ParameterDirection.Output ''''Tham số @KT giả sử là thứ 5
RunSP("sp_Insert_Update_mFaculty ",cnn,Param)
If Param(5).Value=True then
MessageBox.Show("Mã bạn vừa nhập đã tồn tại.Đề nghị bạn nhập mã khác")
End If
Làm thế nào mà khi Nhấn vào tìm kiếm nếu thấy thì
Lưới nhảy đến dòng tìm thấy và các ô textbox nhảy theo
Em đã thử rồi chỉ làm được với textbox nhưng lưới không được
Để làm được điều này Em chỉ cần dùng thuộc tính .Select là được. Cụ thể như sau
If txtHoTen.Text<>"" then
For i as integer=0 to grdName.Rows.Count -1
If txtHoTen.Text=grdName(i,"HoTen") then
grdName.Select(i,True) 'Dòng tìm thấy được chọn
End If
Next
End if
Khi có lệnh grdName.Select(i,True) này lập tức các TextBox trên Form sẽ hiển thị dữ liệu
tương ứng trên lưới thông qua sự kiện grdName_EnterCell()
Em muốn hỏi tại sao Khi chạy Form Login thanh thực đơn UltraToolBar không hiện chỉ
khi ta đóng Form Login nó mấy hiện
Và trong thủ tục Load của Form Main em gọi Form Login
Nhưng không hiểu tại Sao Thực đơn UltraToolBar vẫn không hiện chỉ khi đóng Form nó
mới hiện
Trong form Main khi Em gọi form Login Em dùng thuộc tính Show() thay cho
ShowDialog()
frmLogin.Show()
em tao 1 panel va ben trong co 1 dockmanager (lam menu doc tren MDI form)
Nhung khi chay chuong trinh thi nguoi dung co the click chuot phai vao man hinh MDI
de add Group hoac xoa Group
Va co the thay doi do rong cua panel vay lam the nao de kiem soat viec nay
Thực ra việc Add Group hoặc xóa Group kể cả thêm Button hoặc Toolbar khi Click chuột
phải vào thực chất chỉ là ảo.Tức là những công việc đó chỉ tồn tại và có hiệu lực trong
thời gian mình chạy phần mềm thôi và khi mình thoát phần mềm rồi chạy lại thì những
mục mình đã Thêm ,Xoá vẫn tồn tại.
Em thử chạy Office 2003 mà xem .Nó cũng cho mình thêm,xóa các mục trên menu
những khi chạy lại thì vẫn còn những cái mình đã xoá.
Mình nên để người dùng thay đổi Panel Em ạ. Vì khi độ phân giải màn hình thay đổi thì
Panel sẽ được thay đổi theo.Nếu mình quản lý nó không cho nó thay đổi thì không hay
đâu.
Việc quản lý Thêm , xóa cũng có thể quản lý được nhưng mình cứ để cho người dùng
thêm xóa không sao Em ạ.
em chua cach dung "byref",trong lap trinhem toan dung "byval",nhung co mot so sach
emdoc thay co dung "byref",em thay no chang khac gi "byval",thay co the noi ro hon de
em phan biet ,va thay cho em vi du ve 1 ham nhung dung trong 2 truong hop,1 truong
hop dung "byval",1 truong hop dung "byval"
Trong VB.NET có 2 cách truyền các tham số vào các phương thức (Thủ tục hoặc hàm) là
ByVal (Truyền theo tham trị) và ByRef (Truyền theo tham chiếu) .Hai cách dùng này
hoàn toàn khác nhau chứ không phải giống nhau như Em nghĩ và trong VB.NET mặc
định khi lập trình viên truyền các tham số vào các phương thức nó sẽ là ByVal .Thông
thường thì nên dùng ByVal .
Tong=TinhTong(5+5)
Nếu là ByVal thì sau khi gọi ThayTheByVal(Tong) thì kết quả vẫn là 10
Nhưng nếu là ByRef thì sau khi goi ThayTheByRef(Tong) thì kết quả lại là 5
Em đọc kỹ rồi sẽ hiểu. Tóm lại là .Khi truyền bằng ByVal thì nó sẽ không bị thay đổi
bên trong phương thức còn khi truyền bằng ByRef thì nó sẽ bị thay đổi bên trong phương
thức
Thầy cho em hỏi các nút di chuyển ( Về đầu , Về Cuối , Về Trước , Về Sau và cả nút Huỷ
bỏ thao tác nữa ) phải viết code cho no thế nào ?
Me.BindingContext(ds.Tables("mSchool")).Position
= Me.BindingContext(ds.Tables("mSchool")).Count - 1 ' Về cuối
Sau đó
Dim strConn As String="Server=TenMay ; DataBase=TenDataBase ; User ID =sa ;
Password=sa "
Dim ObjConn As SqlConnection=New SqlConnection(strConn)
ObjConn.Open()
em co hai bảng :
CT1
SoCT char(10) MaK char(10) NgayTT datetime SoTien float CT2 SoCT char(10)
MaHang char(10) MaNV char(10) Bảng CT1 và CT2 liên kết 1-1
param(0).value=me.txtSoCT.text
param(1).value=me.cboMaK.selectedvalue
param(2).value=me.NgayTT.text
param(3).value=me.txtSoTien.text
param(4).value=me.cboMaHang.selectedvalue
param(5).value=me.cboMaNV.selectedvalue
clsDataBase.RunSP("Insert_CT",cnn,param)
getdatagird()
-----------------------------
as
begin
end
if(@@err<>0)...................
---------------------------
---------------------
Em để ý nhé :
Nếu không có @ chắc chắn sẽ báo SoCT is not a parameter for procedure Insert_CT
CT1:
SoCT char(10)
MaK char(10)
NgayTT datetime
SoTien float
CT2:
SoCT char(10)
MaHang char(10)
MaNV char(10)
Em không nên viết Insert vào 2 bảng bằng một thủ tục .Em nên viết bằng TRIGER thì tốt
hơn
Thầy hướng dẫn cho em cách làm một form tìm kiếm sinh viên kết qủa hiện thị trên
Grid (tìm kiêm theo tên trong bảng mStudents)
Em đưa đoạn Code sau vào sự kiện tìm kiếm nhé:
End Sub
Mình có 1 treeview, 1 nút cha và 1 nút con, có 2 contextmenu. Mình không biết cách làm thế
nào để khi nhấn chuột phải vào nút cha thì hiện contextmenu1, nhấn vào nút con thì hiện lên
contextmenu2
Giải thuật là bạn bắt sự kiện MouseDown, nếu là chuột phải thì kiểm tra node dưới con trỏ
chuột là parent hay child rồi show menu tương ứng.
Code demo là C#, bạn chịu khó convert sang VB.EET
if (node.Parent == null)
this.contextMenu1.Show(treeView1, new Point(e.X, e.Y));
else
this.contextMenu2.Show(treeView1, new Point(e.X, e.Y));
//MessageBox.Show(node.Parent.Text);
}
}
khi tôi muốn sử dụng các hàm string như: right, left...thì phải khai báo không gian tên như thế nào?
(System....)
Bạn dùng namespace này:
Imports Microsoft.VisualBasic
Và gọi hàm như sau:
Dim str As String = "test string"
str = Microsoft.VisualBasic.Left(str, 1)
Nếuimport thì không cần khai báo Microsoft.VisualBasic
và ngược lại nếu khai báo thì chỉ việc sử dụng Left(string, string_len)
Tôi dùng môt file CSDL tạm để nạp dữ liệu cần in hóa đơn bán hàng. Mỗi khi in cho khách mới thì
phải xóa dữ liệu đã in cho khách hàng trước đó. Nhưng làm sao để xóa nội dung file đó cho nhanh
(không phải xóa từng dòng)?. Tôi sử dụng CSDL Access, sử dụng kết nối OleDb. Mong các bạn chỉ
dùm
Nếu chương trình của bạn hỗ trợ xử lý truyền thẳng câu lệnh SQL tới DB để chạy thì bạn có
thể truyền câu lệnh DELETE tới DB để xoá các record.
Còn không bạn có thể làm 1 vòng lặp để xoá các record của bạn.
Sử dụng kết nối và đối tượng Command thích hợp rồi truyền thằng cho nó một câu lệnh SQL:
"Delete from tên_bảng" (MySQL) các cơ sở dữ liệu khác là : "delete * from tên_bảng". Nếu
bạn muốn xóa tất cả nội dung của file đó mà không phải là xóa nội dung một bảng thì bạn
truyền câu lệnh SQL: "Drop TABLE tên_bảng" nhưng lần sau thì bạn sẽ lại phải khởi tạo lại
bảng đấy.
Cảm ơn bạn! tôi cũng đã làm đựoc như vậy rồi. Nhưng có vấn đề phát sinh là cần xác định
xem Table đó có tồn tại trong Database không?. Nếu Table đó ko tồn tại mà Drop Table thì sẽ
báo lỗi, ngược lại nếu Table đã có mà dùng Create Table hoặc SELECT ..... INTO Table thì nó
cũng báo lỗi.