|
VB .NET |
| Top 3 Resources | |
| Resource | Advisor.com |
| Resource | VB .Net Heaven |
| Resource | How to do basic file I/O |
| Resource | Got Dot Net |
| Quick Reference | |
| Fill DataGridView | Private
Function FillInternalNotes()
Dim var As New clsVariable() Dim login As New clsLogin Dim conn As SqlConnection = New SqlConnection(login.ConnectStr_WMLData1) conn.Open() Dim myCommand As New SqlCommand myCommand.Connection = conn myCommand.CommandType = CommandType.StoredProcedure myCommand.CommandText = "dbo.spMr_InternalNote_Select_jxm" 'mod_IDmyCommand.Parameters.Add("@mod_ID", SqlDbType.Int, 8) myCommand.Parameters("@mod_ID").Direction = ParameterDirection.Input myCommand.Parameters("@mod_ID").Value = var.ModPointer Dim table As DataTable = New DataTable Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter(myCommand) dataAdapter.Fill(table) dgv1.DataSource = table 'Format Grid dgv1.ColumnHeadersVisible = True dgv1.RowHeadersVisible = False dgv1.Columns(0).Width = 120 dgv1.Columns(1).Width = 360 dgv1.Columns(2).Width = 100 Return 0 End Function
|
| ComboBox with StoredProcedure | Try
'Ct_s_DocCode.DataSource = Nothing Dim login As New clsLoginDim conn As SqlConnection = New SqlConnection(login.ConnectStr_WMLData) Dim com As New SqlCommand com.CommandType = CommandType.StoredProcedure com.CommandText = "dbo.spCt_RefDocs" 'srcfac com.Parameters.Add("@srcfac", SqlDbType.NVarChar, 5) com.Parameters("@srcfac").Direction = ParameterDirection.Input com.Parameters("@srcfac").Value = Me.ct_s_Srcfac.SelectedValue.ToString() Me.Ct_s_DocCode.Items.Clear() com.Connection = conn Dim DataAdpt As New SqlDataAdapter(com) Dim ds As New DataSet DataAdpt.Fill(ds) Ct_s_DocCode.DataSource = ds.Tables(0) Ct_s_DocCode.ValueMember = ds.Tables(0).Columns(0).ToString Ct_s_DocCode.DisplayMember = ds.Tables(0).Columns(1).ToString com = Nothing conn = Nothing Catch MsgBox(Err.Number & " " & Err.Description) Finally End Try
|
| Update DataGridView | Private
Sub TblTelephoneDataGridView_RowLeave(ByVal sender As Object, ByVal e As
System.Windows.Forms.DataGridViewCellEventArgs) Handles
TblTelephoneDataGridView.RowLeave
Me.Validate() TblTelephoneDataGridView.EndEdit(True) TblTelephoneBindingSource.EndEdit() Me.TblTelephoneTableAdapter.Update(Me.DsTelephone) End Sub |
| Pass Null Command Parameter | parameter.value
= dbnull.value
Be sure and set the parameter to null and not a class or other object to null. It must be the parameter that is set to null. |
| DataGrid | Set height to 10 in the page height area even though the display height may be much larger. This will shrink down any small result sets to display well. |
| DataGrid displays carriage return and line feed characters | Select properties dialog for the datagrid. Select "Default Cell Style" Set Wrapmode to true. It is set to false by default. |
| SqlDataReader | Dim myConnectionString = "Initial Catalog=DBName;Server=servername; integrated security = sspi" Dim myConnection As New SqlConnection(myConnectionString) Dim myCommand As New SqlCommand("Select Top 1 bu_date From tblAddOnLog_Backup_Status ORDER BY bu_date DESC", myConnection) myConnection.Open() Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection) While myReader.Read() If Not myReader.IsDBNull(0) Then 'Console.WriteLine(myReader.GetDateTime(0).ToString()) Me.txtAddOns.Text = myReader.GetDateTime(0).ToString() End If End While myReader.Close() |
| Authenticated User Permissions For Web.Config | <authentication
mode="Windows"/>
<identity impersonate="true"/>
<!--
AUTHORIZATION
This section sets the authorization policies of the application. You can allow or deny access to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous (unauthenticated) users. --> <authorization> <allow users="*"/> <!-- Allow all users -->
Set web.config file to these settings and then make sure that the application is running in IIS on the appropriate server. Here localHost IIS can play be a problem if your permissions are different for Server IIS. Either change your permissions to allow authentication to the appropriate user in LocalHost IIS or run the application from the Server IIS Virtual Directory. |
| Refresh | Response.Redirect(Me.ResolveUrl(Request.Url.AbsolutePath)) |
| Events | Multiple
events with the same name but in different languages can fire on the
same event.
ie JavaScript and vb.net |
| AppSettings | <appSettings> <add key="ConnNorthwind" value="server=servername;uid=sa;database=Northwind"/> <add key="ConnectionString" value="server=servername;uid=sa;database=TestDB"/> </appSettings> |
| Code | |
| Dir Function | Dim dir As String Me.ListBox1.Items.Clear() Dim dirs() As String = Directory.GetDirectories(winDir) For Each dir In dirs Me.ListBox1.Items.Add(dir) Next |
| A potentially dangerous virus. Error message. |
Filter User InputIf you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>). To safely allow restricted HTML input
The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.
<%@ Page
Language="C#" ValidateRequest="false"%>
|
| Append Data to DataSet |
Dim dtrow As DataRow dtrow = ds.Tables(0).NewRow() dtrow("sys_id") = -1 dtrow("Name") = String.Empty ds.Tables(0).Rows.InsertAt(dtrow, 0) |
| RollOver |
'lb_mr lb_mr.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_mr.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") 'lb_ma lb_ma.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_ma.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") 'lb_status lb_status.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_status.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") 'lb_ms lb_ms.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_ms.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") 'lb_cp lb_cp.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_cp.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") 'lb_eo lb_eo.Attributes.Add("onmouseover", "this.style.backgroundColor='#004040'") lb_eo.Attributes.Add("onmouseout", "this.style.backgroundColor='teal'") |
| Get Page Name |
Private Function getPage() As String Dim GetCurrentPageName() As String Dim sPath As String = System.Web.HttpContext.Current.Request.Url.AbsolutePath Dim oInfo As System.IO.FileInfo = New System.IO.FileInfo(sPath) Dim sRet As String = oInfo.Name Return sRet End Function Select Case getPage() Case Is = "WebMR_New.aspx" lb_mr.BackColor() = Color.White Case Is = "WebMR_Open.aspx" Me.lb_mgr_approval.BackColor() = Color.White Case Is = "WebMR_Approved.aspx" Me.lb_mgr_approval.BackColor() = Color.White Case Is = "WebMR_Staff.aspx" Me.lb_staff.BackColor() = Color.White Case Is = "WebMR_last.aspx" lb_mr.BackColor() = Color.White Case Is = "WebStatus.aspx" lb_status.BackColor() = Color.White Case Is = "WebStaff.aspx" lb_staff.BackColor() = Color.White Case Else 'Is never used lb_intranet.BackColor() = Color.White End Select |
| App Settings |
<appSettings> <add key="DB:DbName1" value="User ID=***;password=*****;Initial Catalog=DbName1;Server=Corporate1; integrated security = sspi;"/> <add key="DB:DbName2" value="User ID=***;password=*****;Initial Catalog=DbName2;Server=Corporate1; integrated security = sspi;"/> </appSettings> |
| clsUser |
Imports System Imports System.Data.SqlClient Public Class clsUser 'needed for response.write Inherits System.Web.UI.Page Private Shared m_sAdminID As String Private Shared m_sAdminName As String Private Shared m_sAdminDept As String Private Shared m_sAdminSite As Integer Private Shared m_sAdminLevel As String Private Shared m_sProxyID As String Private Shared m_sProxyName As String Private Shared m_sProxyDept As String Private Shared m_sProxySite As String Public Shared Property AdminName() As String Get Return m_sAdminName End Get Set(ByVal Value As String) m_sAdminName = Value End Set End Property Public Shared Property AdminID() As String Get Return m_sAdminID End Get Set(ByVal Value As String) m_sAdminID = Value End Set End Property Public Shared Property AdminDept() As String Get Return m_sAdminDept End Get Set(ByVal Value As String) m_sAdminDept = Value End Set End Property Public Shared Property AdminLevel() As String Get Return m_sAdminSite End Get Set(ByVal Value As String) m_sAdminSite = Value End Set End Property Public Shared Property AdminSite() As Integer Get Return m_sAdminLevel End Get Set(ByVal Value As Integer) m_sAdminLevel = Value End Set End Property Public Shared Property AdminProxyID() As String Get Return m_sProxyID End Get Set(ByVal Value As String) m_sProxyID = Value End Set End Property Public Shared Property AdminProxyName() As String Get Return m_sProxyName End Get Set(ByVal Value As String) m_sProxyName = Value End Set End Property Public Shared Property AdminProxySite() As String Get Return m_sProxySite End Get Set(ByVal Value As String) m_sProxySite = Value End Set End Property Public Shared Property AdminProxyDept() As String Get Return m_sProxyDept End Get Set(ByVal Value As String) m_sProxyDept = Value End Set End Property Public Function UserAuthentication(ByVal empUserID As String, ByVal encryptedPassword As String) UserAuthentication = False Dim usr As clsUser usr = New clsUser Dim login As clsLogin login = New clsLogin Dim strConnection As String strConnection = ConfigurationSettings.AppSettings("DB:DbName") Dim conn As SqlConnection = New SqlConnection(strConnection) Dim SelectQuery As String SelectQuery = "SELECT emp_ID, emp_site, emp_department, emp_password, tblEmployeeApplications.app_name, app_level, emp_first_name + ' ' + emp_last_name as UserName " SelectQuery = SelectQuery & "FROM tblEmployees " SelectQuery = SelectQuery & "JOIN tblEmployeeApplications ON tblEmployees.emp_userid = tblEmployeeApplications.app_userid " SelectQuery = SelectQuery & "WHERE (emp_userid = '" & login.UserID & "' AND emp_password = '" & encryptedPassword & "' AND app_name = '" & login.Application & "' AND emp_active <> 0)" Dim myCommand As New SqlCommand(SelectQuery, conn) conn.Open() Dim myReader As SqlDataReader myReader = myCommand.ExecuteReader() 'Fill usr class While myReader.Read() If Not IsDBNull(myReader.GetInt32(0)) Then usr.AdminID = myReader.GetInt32(0).ToString() usr.AdminSite = myReader.GetInt32(1).ToString() usr.AdminDept = myReader.GetString(2).ToString() usr.AdminLevel = myReader.GetInt32(5).ToString() usr.AdminName = myReader.GetString(6).ToString() UserAuthentication = True End If End While myReader.Close() conn.Close() myCommand.Dispose() End Function End Class |
| To create the example VB.NET Class Library: |
1) Open Visual Studio .NET 2003. 2) Open the File menu, click New, and select Project. 3) In "Project Types", click "Visual Basic Projects", and then click to select "Class Library". 4) Specify MyVBClassLib for the name, and click the OK button. 5) A "Class1.vb" editor window will be opened; close this window. 6) Open Solution Explorer, right-click Class1.cs and select Delete. Click the OK button when you are prompted that it will be permanently deleted. 7) Open the Project menu and select "Properties". 8) In the MyVBClassLib Property Pages dialog, click "Configuration Properties" to expand it, and then click "Build". 9) Place a check mark next to "Register for COM Interop", and then click the OK button to close the properites dialog. 10) Open Solution Explorer again, right-click the MyVBClassLib project (not the "Solution..."), and select Add and "Add New Item". 11) In the "Add New Item" dialog, expand "Local Project Items" under "Categories", and click on "Code". Under "Templates", click "COM Class'. Specify "MyCOMClass.vb" for the name, and click the Open button. 12) A MyCOMClass.vb editor window will open. In the editor window, click the "+" symbol next to "COM GUIDs" to expand this item. Here you can see the guids generated for this class. 13) Farther down in the editor window, you will see the New constructor subroutine for the class. With the New subroutine (before the "End Sub" statement), add the following code:
myHeight = 1 myWidth = 1
CalcArea()
13) Below "End Sub" statement for the New subroutine, add the following statements. This creates several private member variables along with public "properties" functions for getting and
setting their values.
Private myHeight As Double Private myWidth As Double Private myArea As Double
Public Sub CalcArea() myArea = myWidth * myHeight End Sub
Public Property Height() As Double Get Return myHeight End Get Set(ByVal Value As Double) myHeight = Value CalcArea() End Set End Property
Public Property Width() As Double Get Return myWidth End Get Set(ByVal Value As Double) myWidth = Value CalcArea() End Set End Property
Public ReadOnly Property Area() As Double Get Return myArea End Get End Property
14) Open the File menu and choose "Save All". 15) Open the Build menu and choose "Rebuild Solution" (NOTE: since we select "Register for COM Interop" in the project properties earlier, our class is automatically registered for use by COM containers).
===================================================================================================================
To access the class library from VB6: -------------------------------------------------------- 1) Open Visual Basic 6. A default project with a "Project1 - Form1 (Form)" window should automatically be displayed (if not, open the File menu and select "New Project"). 2) In the toolbox window, double-click the button icon to place a button control on the form. This button will be labeled "Command1" by default. Doubleclick this button control to display the
code editor window and place the cursor in the "Command1_Click" event handler subroutine. 3) Open the Project menu and select "References". Scroll the "Available References" list down if you need to, and place a check mark next to "MyVBClassLib". Click the OK button to close the
references dialog. 4) Back inside the Command1_Click event handler, change this routine to look like:
Private Sub Command1_Click() Dim obj As MyVBClassLib.MyCOMClass Set obj = New MyVBClassLib.MyCOMClass
obj.Height = 25.4 obj.Width = 72.34
MsgBox "For height = " + CStr(obj.Height) + " and width = " + CStr(obj.Width) + ", the area is " + CStr(obj.Area) End Sub
5) Save the form and project if you want, but within the VB6 envitonment you can simply click F5 to run this application. Do that now. 6) Clicking F5 will run the application and display the runtime version of Form1. Click the Command1 button and a message box will be displayed showing the text we specified above and the
values for the height, width, and area.
===================================================================================================================
To access the class library from Microsoft Access: -------------------------------------------------------------- 1) Open Microsoft Access. 2) Open the File menu and select New. 3) Select "Blank Database". 4) Give the new database a name a location in the "File New Database" dialog, then click Create. I chose the default "db1.mdb". 5) In the database workspace window, click "Forms" and then double-click "Create Form in Design View". 6) Click on the button icon in the toolbox and then click on the form to place the button. 7) Click the cancel button when the Command Button Wizard appears. 8) Still within Microsoft Access, right-click the button control that you just added to the form and select "Build Event"; then select "Code Builder" and click the OK button. This will open the Visual
Basic editor and will place the cursor inside a Command0_Click subroutine. 9) Within the Visual Basic editor environment, open the Tools menu and select References. Place a check mark next to "VBClassLib" and then click the OK button. 11) Within the Command0_Click subroutine, below the "On Error..." statement, place the following this is the same code we added in the VB6 example above!):
Dim obj As MyVBClassLib.MyCOMClass Set obj = New MyVBClassLib.MyCOMClass
obj.Height = 25.4 obj.Width = 72.34
MsgBox "For height = " + CStr(obj.Height) + " and width = " + CStr(obj.Width) + ", the area is " + CStr(obj.Area)
12) Still in the Visual Basic editor environment, open the File menu and select "Save db1". 13) Open the File menu again and select "Close and Return to Microsoft Office Access". 14) Back in Access, doubleclick Form1 in the database workspace window; this displays the form in run mode. 15) Click the Command0 button. Behind the scenes the Command0_Click handler is executed, and a message box is displayed showing the values that we set through the referenced object.
|