vbdotnet.it

Tricks & tips, workaround, forum and ideas with .Net

About the author

Enrico Rossini è il gestore di questo blog.
E-mail me Send mail

Recent posts

Recent comments

Contributi

Best 6 ~ 6 users ~ 6 comments

Info legali

Le opinioni espresse in questo blog sono strettamente personali e ogni persona è responsabile dei commenti che inserisce. I marchi citati sono delle rispettive aziende.

© Copyright 2010

Advertising


Creare un combobox con ricerca

Per quanto hai cercato un combobox con la possibilità di ricerca? Ecco una semplice implementazione:

Private Sub CombBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
        
Dim findString As String = String.Empty
        
If (Not e.KeyChar.IsLetterOrDigit(e.KeyChar, 0)) Then Exit Sub
        findString = e.KeyChar
        
With ComboBox1
            .SelectedIndex = ComboBox1.FindString(findString)
        
End With
        If ComboBox1.SelectedIndex > -1 Then e.Handled = True
End
Sub

Ciao a tutti!

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Tuesday, September 15, 2009 12:14 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Focus ad un TextBox

Ciao a tutti e buon Ferragosto! (a chi nn lavora). Oggi un veloce tricks: a me è capitato di dover dare il focus ad un textbox ma non compare il cursore all'interno dello stesso.

La funzione più scontata sarebbe TextBox.Focus(). Invece quella che funziona meglio è TextBox.Select(). Provate e verificate voi stessi!

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Saturday, August 15, 2009 12:47 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Invio email con framework 3.5

Con il .NET framework 3.5 è stato introdotto un nuovo namespace Mail per l’invio delle email: questo namespace può essere aggiunto ai nostri programmi con la seguenti riga di codice:

Imports System.Net.Mail

L’invio dell’email può presentare qualche problema poiché non si trovano molti esempi su come inviare ad esempio degli allegati o ricevere una conferma di lettura. Nell’esempio che segue cercherò di rispondere a questi problemi.

Si supponga di avere un form con i seguenti textbox: txtTo per inserire l’email a cui spedire, txtSubject per inserire l’oggetto del messaggio, txtMessage per il corpo del messaggio e un listbox di nome lstAttachment per visualizzare l’elenco degli allegati. Un bottone per l’invio ed un checkbox per voler spedire il messaggio come HTML.

Dim objSmtpMail As System.Net.Mail.SmtpClient       ' variabile generale per l'invio dell'email
Dim Attachment As System.Net.Mail.Attachment        ' variabile per salvare gli allegati
Dim Mailmsg As New System.Net.Mail.MailMessage()    ' variabile per creare il corpo del messaggio
 
Private _displayname As String = ""                 ' variabile che contiene il nome dell'email da visualizzare
Private _from As String = ""                        ' variabile con l'indirizzo email da cui spedire
Private _smtpserver As String = ""                  ' variabile contenente l'indirizzo del server mail
 
Public Sub SendEmail()
   ' imposta le proprietà del server
   objSmtpMail = New System.Net.Mail.SmtpClient(_smtpserver)
 
   ' definisce il mittente 
   ' (primo parametro l'indirizzo email, secondo il nome che deve apparire all'utente che riceve l'email)
   Mailmsg.From = New System.Net.Mail.MailAddress(_from, _displayname)
 
   ' per specificare indirizzi multipli separare uno dall'altro con il ;
   Mailmsg.To.Add(New System.Net.Mail.MailAddress(Me.txtTo.Text.Trim))
 
   ' specifica formato
   If Me.tsbHTML.Checked = True Then
      ' spedisce l'email in formato HTML
      Mailmsg.IsBodyHtml = True
   Else
      Mailmsg.IsBodyHtml = False
   End If
 
   ' aggiunge degli header all'email che consentono di ricevere la conferma di lettura
   Mailmsg.Headers.Add("Reply-To", Mailmsg.From.Address)
   Mailmsg.Headers.Add("Disposition-Notification-To", Mailmsg.From.Address)
   Mailmsg.Headers.Add("Return-Receipt-To", Mailmsg.From.Address)
 
   ' aggiunge il testo
   Mailmsg.Subject = txtSubject.Text
   Mailmsg.Body = txtMessage.Text
 
   ' aggiunte gli allegati
   For Counter = 0 To lstAttachment.Items.Count - 1
      Attachment = New System.Net.Mail.Attachment(lstAttachment.Items(Counter))
      Mailmsg.Attachments.Add(Attachment)
   Next
 
   ' spedisce effettivamente l'email
   objSmtpMail.Send(Mailmsg)
End Sub

Spero vi sia utile. Ciao!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Tuesday, July 21, 2009 12:03 PM
Permalink | Comments (0) | Post RSSRSS comment feed

L'usercontrol è in ambiente di designtime?

Se si è alle prese con la realizzazione di un Usercontrol potrebbe essere utile determinare se il componente stesso si trova in design-time (come ad esempio all’interno di un form in Visual Studio) o se è in runtime.

Per poter verificare questo basta utilizzare il seguente codice:

   1: ' verifica se il componente è in esecuzione a runtime
   2: If System.ComponentModel.LicenseManager.UsageMode = LicenseUsageMode.Runtime Then
   3:    ' esegue altro codice
   4: End If

Ciao.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Thursday, April 16, 2009 7:30 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Leggere un file Microsoft Excel 97/2003 o 2007

La funzione che presento oggi consente di importare un foglio di Microsoft Excel in un dataset nelle versioni 97, 2003 e 2007.

 

   1: ''' <summary>
   2: ''' Reads the data from excel.
   3: ''' </summary>
   4: ''' <param name="excelfilename">The excelfilename.</param>
   5: ''' <returns></returns>
   6: Function ReadDataFromExcel(ByVal excelfilename As String) As DataSet
   7:     Dim ds As New DataSet
   8:     Dim da As OleDbDataAdapter
   9:     Dim conn As OleDbConnection
  10:  
  11:     Try
  12:         If System.IO.Path.GetExtension(excelfilename) = ".xls" Then
  13:             conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  14:         ElseIf System.IO.Path.GetExtension(excelfilename) = ".xlsx" Then
  15:             conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & excelfilename & "; Extended Properties=Excel 8.0;")
  16:         End If
  17:  
  18:         da = New OleDbDataAdapter("SELECT * FROM [Foglio1$]", conn)
  19:  
  20:         conn.Open()
  21:         da.Fill(ds)
  22:     Catch ex As Exception
  23:         MsgBox(ex.Message)
  24:     Finally
  25:         If conn.State = ConnectionState.Open Then
  26:             conn.Close()
  27:         End If
  28:     End Try
  29:     ReadDataFromExcel = ds
  30: End Function

Buon lavoro e ricordatevi il nostro forum!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Tuesday, April 07, 2009 7:32 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Leggere\Scrivere un testo da un file di testo

Io non mi ricordo mai come leggere o scrivere un file di testo: ho ritenuto quindi di creare un post con due funzioni che possono essere utili.

   1: Imports System.IO
   2:  
   3: ' funzione di lettura del contenuto di un file
   4: Public Function GetFileContents(ByVal FullPath As String, _
   5:        Optional ByRef ErrInfo As String = "") As String
   6:         Dim strContents As String
   7:         Dim objReader As StreamReader
   8:         Try
   9:             objReader = New StreamReader(FullPath)
  10:             strContents = objReader.ReadToEnd()
  11:             objReader.Close()
  12:             Return strContents
  13:         Catch Ex As Exception
  14:             ErrInfo = Ex.Message
  15:         End Try
  16: End Function
  17:  
  18: ' funzione per il salvataggio di un testo in un file
  19: Public Function SaveTextToFile(ByVal strData As String, _
  20:      ByVal FullPath As String, _
  21:        Optional ByVal ErrInfo As String = "") As Boolean
  22:  
  23:         Dim Contents As String
  24:         Dim bAns As Boolean = False
  25:         Dim objReader As StreamWriter
  26:         Try
  27:             objReader = New StreamWriter(FullPath)
  28:             objReader.Write(strData)
  29:             objReader.Close()
  30:             bAns = True
  31:         Catch Ex As Exception
  32:             ErrInfo = Ex.Message
  33:         End Try
  34:         Return bAns
  35: End Function

 

Per poter utilizzare questo codice si può seguire il seguente esempio:

   1: sContents = GetFileContents("C:\test.txt", sErr)
   2: If sErr = "" Then
   3:    Debug.WriteLine("File Contents: " & sContents)
   4:    ' salva in un file differente
   5:    bAns = SaveTextToFile(sContents, "D:\Test.txt", sErr)
   6:    If bAns Then
   7:       Debug.WriteLine("File Saved!")
   8:    Else
   9:       Debug.WriteLine("Error Saving File: " & sErr)
  10:    End If
  11: Else
  12:    Debug.WriteLine("Error retrieving file: " & sErr)
  13: End If

Buon lavoro!

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Monday, February 23, 2009 1:13 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Script SQL To Code

Ciao a tutti! A me capita che devo inserire nei miei programmi del codice SQL per la creazione di tabelle e non riesco mai a trovare un programma che mi genera un file Visual Basic.NET che mi piaccia. Allora mi lo sono creato. Semplice e fa quello che voglio: per ogni tabella crea una funzione con il nome della tabella e al termine mi crea una funzione AllDatabase che richiama tutte le tabelle. Ogni funzione fa riferimento alla funzione ExecuteCommand che può essere facilmente implementata anche seguento leindicazione che trovate in un altro mio post. Come fare per generare corretamente un file?

  1. Creare ad esempio da SQL Server lo script di generazione delle tabelle.
  2. Eliminare riferimento a SET ANSI_NULL e SET QUOTE_IDENTIFIER con i relativi GO
  3. Copiare lo script rimanente nel programma

Buon lavoro!

ScriptToCode.zip (10,33 kb)

 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: sql | vb.net | windowsform
Posted by enrico on Monday, February 23, 2009 12:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Come conoscere l'ID della scheda madre?

Questa funzione consente di conoscere l’identificativo del processore montato sul PC. Per poter eseguire correttamente questa funzione è necessario importare il namespace System.Management

   1:  Imports System.Management
   2:   
   3:  Public Function GetMotherBoardID() As String
   4:     Dim strMotherBoardID As String = String.Empty
   5:     Dim query As New SelectQuery("Win32_BaseBoard")
   6:     Dim search As New ManagementObjectSearcher(query)
   7:   
   8:     For Each info As ManagementObject In search.Get()
   9:        strMotherBoardID = info("SerialNumber").ToString()
  10:     Next
  11:   
  12:     Return strMotherBoardID
  13:  End Function

È possibile modificare questa funzione e trovare altre informazioni sul sistema.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Sunday, December 28, 2008 10:57 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Come conoscere l'ID del processore?

Questa funzione consente di conoscere l’identificativo del processore montato sul PC. Per poter eseguire correttamente questa funzione è necessario importare il namespace System.Management

   1:  Imports System.Management
   2:   
   3:  Public Function GetProcessorId() As String
   4:     Dim strProcessorId As String = String.Empty
   5:     Dim query As New SelectQuery("Win32_processor")
   6:     Dim search As New ManagementObjectSearcher(query)
   7:   
   8:     For Each info As ManagementObject In search.Get()
   9:        strProcessorId = info("processorId").ToString()
  10:     Next
  11:   
  12:     Return strProcessorId
  13:  End Function

Questa funzione può essere modificata per conoscere altre informazioni sulla macchina.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by enrico on Sunday, December 28, 2008 10:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Convert Script in Code

Ho girato tutta interet ma non ho trovato un semplice programmino che mi consente di trasformare uno script SQL in un banale codice VB.NET.  Quindi ho deciso di realizzarlo e metterlo a disposizione di chiunque. Spero vi possa essere utile. Dopo aver inserito lo script SQL (o qualsiasi altro script) ed il nome della variabile, si può convertire in VB.NET.

Nella finestra sotto appare il codice e può essere copiato nella clipboard direttamente.

ConvertInCode.zip (9,80 kb)

 

Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: vb.net | windowsform
Posted by enrico on Sunday, September 28, 2008 11:07 PM
Permalink | Comments (0) | Post RSSRSS comment feed