working on it ...

Filters

Explore Public Snippets

Sort by

Found 147 snippets matching: vb.net

    public by Uriahs modified Jun 29, 2015  310202  1  6  0

    Move borderless form VB.NET

    Code to move a borderless winform which is not moveable by default
    Dim drag As Boolean
       Dim mousex As Integer
       Dim mousey As Integer
       Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
           drag = True 'Sets the variable drag to true.
           mousex = Windows.Forms.Cursor.Position.X - Me.Left 'Sets variable mousex
           mousey = Windows.Forms.Cursor.Position.Y - Me.Top 'Sets variable mousey
       End Sub
    
       Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
           'If drag is set to true then move the form accordingly.
           If drag Then
               Me.Top = Windows.Forms.Cursor.Position.Y - mousey
               Me.Left = Windows.Forms.Cursor.Position.X - mousex
           End If
       End Sub
    
       Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
           drag = False 'Sets drag to false, so the form does not move according to the code in MouseMove
       End Sub
    

    public by zonaro modified Oct 28, 2015  196896  0  8  0

    Sum (Excel port for VB.NET)

    Like in Excel, this method sum the numbers of a ParamArray
    Function Sum(ByVal ParamArray Nums As Decimal()) As Decimal
            Dim s = 0
            For Each i As Decimal In Nums
                s += i
            Next
            Return s
        End Function            

    public by Uriahs modified Aug 30, 2015  1859  0  5  0

    Simple MySQL database connection with select statement

    This snippet has coode to pull the rows from the db in a while loop.
      'Import this to the very top of your code, make sure you have the mysql connector installed for VS
      
      Imports mysql.data.mysqlclient
      
      Dim conn As New MySqlConnection
            Dim cmd As New MySqlCommand
            Dim read As MySqlDataReader
    
    
    
            Try
    			'default root would have no pw...simply remove the password part if you have no pw
                conn.ConnectionString = "server=127.0.0.1;user id=root; password=yourpw; database=mydb"
    
    
                cmd.Connection = conn
    
    
                conn.Open()
                cmd.CommandText = "SELECT id, name FROM mydb.table"
                read = cmd.ExecuteReader
    
                If read.HasRows Then
    
                    While read.Read
    					'name this variable anything you want
                        Dim id = read.GetInt32("id")
                        
                        'for getting a string value:
                        Dim sName = read.GetString("name")
    					
    					'make the pvname and pvid public(global) variables so you could use them outside while loop,
    					'this might not be needed in some cases
    		
                        pvname = sName 
                        pvid = id
                    End While
    
                End If
    
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            
            

    public by marksimon232 modified Jun 23, 2014  2472  1  6  1

    Data access onto DB in VB.NET 2010

    Code that will save,delete,search,next and back data to Access database in vb.net 2010
    Could you please try this to get things done for you?
    
    
    using System;
    using System.Data;
    using System.Data.Common;
    using System.Data.OleDb;
    
    class MainClass
    {
      static void Main(string[] args)
      {
        string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\Northwind.mdb";
    
        OleDbConnection conn = new OleDbConnection(connectionString);
    
        string sql = "SELECT * FROM Orders";
    
        OleDbCommand cmd = new OleDbCommand(sql, conn);
    
        conn.Open();
    
        OleDbDataReader reader;
        reader = cmd.ExecuteReader();
    
        while (reader.Read()) 
        {
          Console.Write(reader.GetString(0).ToString() + " ," );
          Console.Write(reader.GetString(1).ToString() + " ," );
          Console.WriteLine("");
        }
    
        reader.Close();
        conn.Close();
      }
    }

    public by marksimon232 modified Jun 23, 2014  2204  1  6  0

    VB.NET 2010 to connect to ms access database

    Grabs data from a table and posts it into a ListView
    
    Dim Table_ As String = "Table1"
    Dim query As String = "SELECT * FROM " & Table_
    Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TestDatabase.mdb;"
    Dim ds As New DataSet
    Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_)
    
    cnn.Open()
    Dim cmd As New OleDbCommand(query, cnn)
    Dim da As New OleDbDataAdapter(cmd)
    da.Fill(ds, Table_)
    cnn.Close()
    
    Dim t1 As DataTable = ds.Tables(Table_)
    Dim row As DataRow
    Dim Item(2) As String
    
    For Each row In t1.Rows
        Item(0) = row(0)
        Item(1) = row(1)
        Dim NextListItem As New ListViewItem(Item)
    
        ListView1.Items.Add(NextListItem)
    Next

    public by Uriahs modified Jul 1, 2015  2124  1  6  0

    Change default VS webbrowser render engine

    Perfect for websites sending out js errors !
    create a form called Form1 or just name accordingly, delete everything with its code and paste with below, now you will be surfing using the current installed IE   
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            CreateBrowserKey()
           
    'Below code adds a custom useragent, adding a custom useragent does not change the actual engine...thats why we need to do all this coding.
    WebBrowser1.Navigate("http://www.whatsmybrowser.org", "_top", Nothing, "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36")
    
    'This goes to the website using default user agent.
       'WebBrowser1.Navigate("http://www.whatsmybrowser.org")
    
        End Sub
    
        Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
            RemoveBrowerKey()
        End Sub
        Private Const BrowserKeyPath As String = "\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION"
        Private Sub CreateBrowserKey(Optional ByVal IgnoreIDocDirective As Boolean = False)
            Dim basekey As String = Microsoft.Win32.Registry.CurrentUser.ToString
            Dim value As Int32
            Dim thisAppsName As String = My.Application.Info.AssemblyName & ".exe"
            ' Value reference: http://msdn.microsoft.com/en-us/library/ee330730%28v=VS.85%29.aspx
            ' IDOC Reference:  http://msdn.microsoft.com/en-us/library/ms535242%28v=vs.85%29.aspx
            Select Case (New WebBrowser).Version.Major
                Case 8
                    If IgnoreIDocDirective Then
                        value = 8888
                    Else
                        value = 8000
                    End If
                Case 9
                    If IgnoreIDocDirective Then
                        value = 9999
                    Else
                        value = 9000
                    End If
                Case 10
                    If IgnoreIDocDirective Then
                        value = 10001
                    Else
                        value = 10000
                    End If
    
                Case 11
                    If IgnoreIDocDirective Then
                        value = 11001
                    Else
                        value = 11000
                    End If
                Case Else
                    Exit Sub
            End Select
            Microsoft.Win32.Registry.SetValue(Microsoft.Win32.Registry.CurrentUser.ToString & BrowserKeyPath, _
                                              Process.GetCurrentProcess.ProcessName & ".exe", _
                                              value, _
                                              Microsoft.Win32.RegistryValueKind.DWord)
        End Sub
        Private Sub RemoveBrowerKey()
            Dim key As Microsoft.Win32.RegistryKey
            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(BrowserKeyPath.Substring(1), True)
            key.DeleteValue(Process.GetCurrentProcess.ProcessName & ".exe", False)
        End Sub
    
    End Class

    public by sherazkhan modified Nov 11, 2015  2036  0  6  0

    How to Send Email Messages using DNS inside C# & VB.NET Apps

    This technical tip explains how to send an email messages using DNS inside .NET applications. Sometimes sending mails using an SMTP server is not feasible for a project’s requirement. We may want to utilize the MX record of the recipient’s domain name.
    // Enter here the actual content of the snippet.            
    static void Main(string[] args)
    {
        try
        {
            MailMessage msg = new MailMessage("add1@domain.com", "add1@domain.com", "test", "this is a test");
            msg.CC.Add(new MailAddress("add2@domain.com", "CC Display Name"));
            DnsSendMessage(msg);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    
        Console.WriteLine("Program finished. Press any key to exit....");
        Console.ReadKey();
    }
    
    /// <summary>
    /// Use for sent message
    /// </summary>
    /// <param name="msg">message to send</param>
    /// <returns></returns>
    private static void DnsSendMessage(MailMessage msg)
    {
        // Get all the recipients in to, cc and bcc in one collection
        MailAddressCollection addresses = new MailAddressCollection();
        foreach (MailAddress to in msg.To)
        {
            addresses.Add(to);
        }
        foreach (MailAddress cc in msg.CC)
        {
            addresses.Add(cc);
        }
        foreach (MailAddress bcc in msg.Bcc)
        {
            addresses.Add(bcc);
        }
    
        // send mail using DNS to each address
        foreach (MailAddress addr in addresses)
        {
            //Find mail exchange servers with the help of DnsClient
            DnsClient dnsClient = new DnsClient();
            Question mxQuestion = new Question(addr.Host, QueryType.MX);
            if (dnsClient.Resolve(mxQuestion))
            {
                // try to send a message
                foreach (ResourceRecord record in dnsClient.ReceivedMessage.Answers)
                {
                    MXResourceRecord cnRecord = record as MXResourceRecord;
                    if (cnRecord != null)
                    {
                        try
                        {
                            // Send message
                            SmtpClient client = new SmtpClient();
                            client.AuthenticationMethod = SmtpAuthentication.None;
                            client.Host = cnRecord.ExchangeName;
                            client.Port = 25;
                            client.Send(msg);
                            Console.WriteLine("Mail sent to " + addr.Address);
                        }
                        catch (SmtpException e)
                        {
                            Console.WriteLine(cnRecord.ExchangeName + ": " + e.Message + Environment.NewLine);
                            continue;
                        }
                    }
                }
            }
        }
    }
    

    public by p.kontalis modified Mar 4, 2016  2675  0  4  0

    Batch Control Style

    Example regarding the control styling. This example applies a new color on all the buttons of your current form.
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      btn = Me.Controls.OfType(Of Button)().Where(Function(c) c.Name.Contains("")).ToArray()
    End Sub
    
    Private Sub Recolor()
      Dim i As Integer = 0
      While i < btn.Count
        btn(i).Enabled = True
        btn(i).BackColor = Color.Yellow
        i += 1
      End While
    End Sub
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Recolor()
    End Sub

    public by zonaro modified Oct 28, 2015  2191  0  7  0

    Greeting or farewell according to the current time (Saudação ou despedida de acordo com o horário atual)

    Returns a text containing the greeting or farewell to the specified language (English, Portuguese or Spanish. Default language is Portuguese) Retorna um texto contendo a saudação ou despedida de acordo com o idioma especificado (Português, Inglês ou Espanhol. Idioma padrão é português)
    //see this and other methods compiled 
    //into a DLL in http://github.com/kaizonaro/innerlibs.net/releases/
    
    
    Public Function Greeting(Optional Language As String = "pt", Optional Farewell As Boolean = False) As String
    
           Dim bomdia As String = "Bom dia"
           Dim boatarde As String = "Boa tarde"
           Dim boanoite As String = "Boa noite"
           Dim boanoite_despedida As String = boanoite
           Dim seDespedidaManha As String = "tenha um ótimo dia"
           Dim seDespedidaTarde As String = "tenha uma ótima tarde"
    
           Select Case Language.ToLower()
               Case "en", "eng", "ingles", "english"
                   bomdia = "Good morning"
                   boatarde = "Good afternoon"
                   boanoite = "Good evening"
                   boanoite_despedida = "Good night"
                   seDespedidaManha = "have a nice day"
                   seDespedidaTarde = "have a great afternoon"
                   Exit Select
               Case "es", "esp", "espanhol", "espanol", "español", "spanish"
                   bomdia = "Buenos días"
                   boatarde = "Buenas tardes"
                   boanoite = "Buenas noches"
                   boanoite_despedida = boanoite
                   seDespedidaManha = "que tengas un buen día"
                   seDespedidaTarde = "que tengas una buena tarde"
                   Exit Select
           End Select
    
           If DateTime.Now.Hour > 6 AndAlso DateTime.Now.Hour < 12 Then
               Return If(Farewell, seDespedidaManha, bomdia)
           ElseIf DateTime.Now.Hour >= 12 AndAlso DateTime.Now.Hour < 18 Then
               Return If(Farewell, seDespedidaTarde, boatarde)
           Else
               Return If(Farewell, boanoite_despedida, boanoite)
           End If
       End Function
       
                            

    public by zonaro modified Oct 28, 2015  2004  1  6  0

    Toggle Method for Integer and Boolean Types (Extension Method)

    Allow you to use Variable.Toggle() to invert the current value of a Boolean Variable. Also works with Integer type too!
    Public Module Toggles
         
        <Extension()>
        Public Sub Toggle(ByRef Bool As Boolean)
            Bool = Not Bool
        End Sub
        
        <Extension()>
        Public Sub Toggle(ByRef Int As Integer)
            If Int > 0 Then
                Int = 0
            Else
                Int = 1
            End If
        End Sub 
    End Module
    • Public Snippets
    • Channels Snippets