Monday, August 26, 2013


converting datatable/datagrid view to html in vb.net

Following code snippet can be used for finding html from a datatable in vb.net. this code is very useful in many situation such as if you need to send a datatable through email then we can find html of that datatable and can send html body.

Do the imports of 

Imports System.Text


variables 
declaration

 Public DatabasePath As String

1.this is my function where i populate the datatable

Public Function populateGrid(ByVal sql As String, ByVal dg As DataGridView) As DataTable
        Dim strCnxn As String
        strCnxn = getdbpath()
        Dim xDataSet As DataSet = New DataSet
        Dim sConnect As String = strCnxn
        Dim xSqlConnection As SqlConnection = New SqlConnection(sConnect)
        Try
            Dim cmdString As String = "select * from alert_data_master (nolock)"
            Dim xSqlCommand As New SqlCommand(cmdString, xSqlConnection)
            xSqlCommand = New SqlCommand("alert_popup_qry", xSqlConnection)
            xSqlCommand.CommandType = CommandType.StoredProcedure
            xSqlCommand.Parameters.Add(New SqlParameter("@flg", OleDbType.BSTR))
            xSqlCommand.Parameters("@flg").Value = ""
            xSqlConnection.Open()
            Dim xSqlDataAdapter As SqlDataAdapter = New SqlDataAdapter(xSqlCommand)
            xSqlDataAdapter.Fill(xDataSet)
            Dim dt As New DataTable("Table1")
            xDataSet.Tables.Add(dt)
            dg.DataSource = xDataSet.Tables(0)
            populateGrid = xDataSet.Tables(0)
            xSqlDataAdapter.Dispose()
            xSqlConnection.Close()
        Catch xError As Exception
            ' Handle Error here!
            If Err.Number = 5 Then
                MsgBox(Err.Description)
                End
            Else
                MsgBox(Err.Description)
            End If
            Throw
        Finally
            If Not (xSqlConnection Is Nothing) Then xSqlConnection.Close()
            xSqlConnection.Dispose()
            xSqlConnection.Close()
        End Try
    End Function

2. Here is my database connectivity. Here i use a registry entry to get the connection string.

    Public Function getdbpath() As String
        'My.Computer.Registry.CurrentUser.CreateSubKey("DB_Path")
        'My.Computer.Registry.SetValue("HKEY_CURRENT_USER\DB_Path", "DbPath", "Persist Security Info=False;User ID=sa;pwd=sqlpassw0rd;Initial Catalog=AlertMgmt;Data Source=ITTEST\ITTEST2008")
        Dim readValue As String
        readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\DB_Path", "DbPath", Nothing)
        'MsgBox("The value is: " & readValue)
        DatabasePath = readValue
        getdbpath = DatabasePath
        Return getdbpath
    End Function
3. Here is the function to convert the datatable to the html format.


    Public Shared Function ConvertToHtmlFile(ByVal myTable As DataTable) As String
        Dim myHtmlFile As String = ""
        Dim myBuilder As New StringBuilder

        If myTable Is Nothing Then
            Throw New System.ArgumentNullException("myTable")
        Else
            'Continue. }
            'Get a worker object. StringBuilder myBuilder = new StringBuilder();
            'Open tags and write the top portion. 
            myBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>")
            myBuilder.Append("<head>")
            myBuilder.Append("<title>")
            myBuilder.Append("Page-")
            myBuilder.Append(Guid.NewGuid().ToString())
            myBuilder.Append("</title>")
            myBuilder.Append("</head>")
            myBuilder.Append("<body>")
            myBuilder.Append("<br />  <table border='1px' cellpadding='5' cellspacing='0' ")
            myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>")
            'Add the headings row.
            myBuilder.Append("<br /><tr align='left' valign='top'>")
            For Each myColumn As DataColumn In myTable.Columns
                myBuilder.Append("<br /><td align='left' valign='top' style='border: solid 1px blue;'>")
                myBuilder.Append(myColumn.ColumnName)
                myBuilder.Append("</td><p>")
            Next
            myBuilder.Append("</tr><p>")
            'Add the data rows. foreach (DataRow myRow in myTable.Rows) {  myBuilder.Append("<br />
            '<tr align='left' valign='top'>");
            For Each myRow As DataRow In myTable.Rows
                myBuilder.Append("<br /><tr align='left' valign='top'>")
                For Each myColumn As DataColumn In myTable.Columns
                    myBuilder.Append("<br /><td align='left' valign='top' style='border: solid 1px blue;'>")
                    myBuilder.Append(myRow(myColumn.ColumnName).ToString())
                    myBuilder.Append("</td><p>")
                Next
            Next
            myBuilder.Append("</tr><p>")
        End If
        'Close tags. 
        myBuilder.Append("</table><p>")
        myBuilder.Append("</body>")
        myBuilder.Append("</html>")
        'Get the string for return. myHtmlFile = myBuilder.ToString();
        myHtmlFile = myBuilder.ToString()
        MsgBox(myHtmlFile)
        Return myHtmlFile
    End Function


source: www.authorcode.com/ and i have modified in my own way.

Monday, August 12, 2013

Posted: 12 Aug 2013 03:35 AM PDT
Many countries (such as Iran, North Korea, United Kingdom, The Netherlands, Belgium, Finland, Denmark, Italy, Ireland etc.) and ISP's block file-sharing websites like ThePirateBay, to get over the censorship numerous TPB proxies are already there. But celebrating their 10th birthday, TPB released the PirateBrowser - a single-click, portable web-browser which circumvents censorship and blockades and makes the site instantly available and accessible everywhere. The browser is 100% safe and comes without any bundled ad-ware, toolbars or other crap.

Download PirateBrowser

Version 0.6b

FAQ

Does it make me surf the net anonymously?

No, it's not inteneded to be a TOR Browser, while it uses the Tor network, which is designed for anonymous surfing, this browser is ONLY intended to circumvent censorship.
The Tor network is used to help route around the censoring / blocking of websites your government doesn't want you to know about.

If you are looking for something more secure you may want to try a VPN like PrivacyIO.

Does this contain any viruses or trojans?

There have been no modifications to any of the packages used, no adware, trojans, toolbars, etc. This is simply a tool to help people get around censorship.

Getting Started

  • 1) Download PirateBrowser and save it to your computer:

  • 2) Run the downloaded .exe file

    You may be prompted to verify the application, press "Run":
  • 3) Select the desination folder and press "Extract":


    (It will create a PirateBrowser folder in the path you assign)
  • 4) Go to the new directory and run the "Start PirateBrowser.exe" file:

  • 5) The application will start up. Once connected to the Tor Network the standalone Firefox browser will open up and you can start browsing:


  • TIP: If you want to create a icon on your desktop to start the PirateBrowser, you can right click on "Start PirateBrowser.exe", choose "Send to" and then "Desktop (create shortcut)".
 
source :Megaleecher.Net PirateBrowser

Tuesday, August 6, 2013



Creating multiple column combobox.



http://social.msdn.microsoft.com/Forums/windows/en-US/20840c53-f222-444e-9866-30517bb7f79e/multiple-columns-combo-box-vbnet

1. create a usercontrol
   2 Replace all the code with the code below
   3 build project, now on the my usercontrols tab on the toolbox there is a multicolumnCombo
   4 drop a instance on a form, a set as usualy value,display member, datasource etc.
   5 check if drawmode is set to ownerdrawfixed
   6 set the columnwidths property like this
      example: if you got 3 column from the datasource  and you want to hide
                   the second
                  100;0;140 (first column 100 px 2nd 0 px and 3rth 140 px)
   7 run : tada !!!


the code :




class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; mso-layout-grid-align: none">'Courier New'">Imports System.Drawing.Drawing2D
Imports System.Windows
Public Class MultiColumnCombo
    Inherits System.Windows.Forms.ComboBox
    Private _ColumnWidths As String = "100"
    Private _ColumnWidthsArray As String()
    Private _DoNotReact As Boolean = False
    Private _Textchanged As Boolean = False
    Sub New()
        MyBase.New()
        MyBase.DrawMode = DrawMode.OwnerDrawFixed
        'SetStyle(ControlStyles.UserPaint, True)
        'SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        'SetStyle(ControlStyles.DoubleBuffer, True)
    End Sub


    Public Property ColumnWidths() As String
        Get
            Return _ColumnWidths
        End Get
        Set(ByVal Value As String)
            _ColumnWidths = Value
            _ColumnWidthsArray = Value.Split(CType(";", Char))
            Dim w As Integer = 0
            For Each str As String In _ColumnWidthsArray
                w += CInt(str)
            Next str
            MyBase.DropDownWidth = w + 10
        End Set
    End Property

    Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
        ' Set the DrawMode property to draw fixed sized items.

        '
        'If _Textchanged Then
        '    _Textchanged = False
        '    Exit Sub
        'End If

        Dim myBrush As Brush
        'If e.Bounds.Y = 0 Then
        '    ItemHeight = 32
        'Else
        '    ItemHeight = 16
        'End If
        '  e.DrawBackground()
        Dim LightColor As Color = Color.Blue
        Dim DarkColor As Color = Color.Black
        Dim GradBrush As Brush = New LinearGradientBrush(e.Bounds, LightColor, DarkColor, LinearGradientMode.Vertical)



        Select Case CInt((e.State And DrawItemState.Selected))
            'Case DrawItemState.Selected + DrawItemState.NoAccelerator + DrawItemState.NoFocusRect, DrawItemState.Selected
        Case DrawItemState.Selected
                myBrush = New SolidBrush(BackColor)
                e.Graphics.FillRectangle(GradBrush, e.Bounds)
            Case Else
                myBrush = New SolidBrush(ForeColor)
                'myBrush = GradBrush
                e.Graphics.FillRectangle(New SolidBrush(BackColor), e.Bounds)
        End Select



        Dim str As String
        ' Draw the current item text based on the current Font and the custom brush settings.
        Dim row As DataRowView = (CType(MyBase.Items(e.Index), DataRowView))
        Dim newpos As Integer = e.Bounds.X
        Dim endpos As Integer = e.Bounds.X

        For indx As Integer = 0 To UBound(_ColumnWidthsArray)
            Dim ColLength As Integer = CType(_ColumnWidthsArray(indx), Integer)
            endpos += ColLength

            Dim Charaant As Integer = CInt(Math.Round(CDbl(ColLength) / 6.2))
            Dim rawitem As String = row.Item(indx).ToString()

            If ColLength <> 0 Then


                If Charaant > rawitem.Length Then
                    str = rawitem

                Else

                    str = rawitem.Substring(0, Charaant)
                End If

                Dim r As RectangleF = New RectangleF(newpos + 2, e.Bounds.Y, endpos - 1, e.Bounds.Height)

                'e.Graphics.FillRectangle(myBrush, r)

                e.Graphics.DrawString(str, e.Font, myBrush, r)

                'ControlPaint.DrawBorder3D(e.Graphics, New Rectangle(endpos + 2, e.Bounds.Y, newpos, e.Bounds.Height))
                'e.Graphics.DrawString("mycol", e.Font, myBrush, New RectangleF(newpos, 0, CInt(_ColumnWidthsArray(indx)), ItemHeight))
                If indx <= UBound(_ColumnWidthsArray) Then
                    e.Graphics.DrawLine(New Pen(Color.Black), endpos, e.Bounds.Y, endpos, Me.ItemHeight * Me.MaxDropDownItems)
                    e.Graphics.DrawLine(New Pen(Color.LightGray), endpos + 1, e.Bounds.Y, endpos + 1, Me.ItemHeight * Me.MaxDropDownItems)
                End If
            End If

            newpos = endpos
        Next
        '        e.DrawFocusRectangle()
        myBrush.Dispose()
        GradBrush.Dispose()


    End Sub

    Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)

        Dim foundIndex As Integer, textlngth As Integer
        If _DoNotReact = False Then
            If Me.AccessibilityObject.Value Is Nothing Then
                textlngth = 0
                Exit Sub
            Else
                textlngth = Me.AccessibilityObject.Value.Length
            End If

            If textlngth = 0 Then
                MyBase.OnTextChanged(e)
                _DoNotReact = False
                _Textchanged = False
                Exit Sub
            End If

            If textlngth <> 0 Then

                _DoNotReact = True
                foundIndex = FindString(Me.AccessibilityObject.Value)
                If foundIndex > -1 Then
                    Me.SelectedIndex = foundIndex
                    Me.Select(textlngth, Me.Text.Length - textlngth)
                    'Me.SelectionStart = textlngth
                    _Textchanged = True
                Else
                    _Textchanged = False
                End If
                _DoNotReact = False
            End If
            MyBase.OnTextChanged(e)
        End If
        _DoNotReact = False



    End Sub

    Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
        Select Case e.KeyCode
            Case Keys.Back, Keys.Enter, Keys.Delete
                _DoNotReact = True
            Case Keys.Down
                Me.DroppedDown = True
                Invalidate()

        End Select

        MyBase.OnKeyDown(e)

    End Sub


End Class

Monday, August 5, 2013

DataGridView.SelectionChanged Event

Microsoft MSDN.link.

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionchanged.aspx


'Declaration
Public Event SelectionChanged As EventHandler
This event occurs whenever cells are selected or the selection is canceled, whether programmatically or by user action. For example, this event is useful when you want display the sum of the currently selected cells.
When you change the value of the CurrentCell property, the SelectionChanged event occurs before the CurrentCellChanged event. Any SelectionChanged event handler accessing the CurrentCell property at this time will get its previous value.
For more information about handling events, see Consuming Events.
The following code example demonstrates the use of this event. In the example, the form displays the sum of values in the selected cells, and updates the sum when the selection changes.
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Private WithEvents DataGridView1 As New DataGridView()
    Private FlowLayoutPanel1 As New FlowLayoutPanel()
    Private Label1 As New Label()
    Private Label2 As New Label()
    Private Label3 As New Label()
    Private Label4 As New Label()

    ' Establish the main entry point for the application.
    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub 

    Public Sub New()

        ' Set the FlowLayoutPanel1 properties. 
        With Me
            .AutoSize = True 

            With .FlowLayoutPanel1
                .FlowDirection = FlowDirection.TopDown
                .Location = New System.Drawing.Point(354, 0)
                .AutoSize = True
                .Controls.Add(Label1)
                .Controls.Add(Label2)
                .Controls.Add(Label3)
                .Controls.Add(Label4)
            End With

            .Controls.Add(Me.FlowLayoutPanel1)
            .Controls.Add(DataGridView1)


            ' Set the Label properties.
            .Label1.AutoSize = True
            .Label2.AutoSize = True
            .Label3.AutoSize = True

            .PopulateDataGridView()
            .UpdateLabelText()
            .UpdateBalance()
        End With 
    End Sub 

    ' Replace this with your own code to populate the DataGridView. 
    Private Sub PopulateDataGridView()
        With Me.DataGridView1
            .Size = New Size(350, 400)
            .AllowUserToDeleteRows = True 

            ' Add columns to the DataGridView.
            .ColumnCount = 4
            .SelectionMode = DataGridViewSelectionMode.RowHeaderSelect

            ' Set the properties of the DataGridView columns.
            .Columns(0).Name = "Description"
            .Columns(1).Name = "Withdrawals"
            .Columns(2).Name = "Deposits"
            .Columns(3).Name = "Balance"
            .Columns("Description").HeaderText = "Description"
            .Columns("Withdrawals").HeaderText = "W(-)"
            .Columns("Deposits").HeaderText = "D(+)"
            .Columns("Balance").HeaderText = "Balance"
            .Columns("Balance").ReadOnly = True
            .Columns("Description").SortMode = _
                DataGridViewColumnSortMode.NotSortable
            .Columns("Withdrawals").SortMode = _
                DataGridViewColumnSortMode.NotSortable
            .Columns("Deposits").SortMode = _
                DataGridViewColumnSortMode.NotSortable
            .Columns("Balance").SortMode = _
                DataGridViewColumnSortMode.NotSortable
        End With 

        ' Add rows of data to the DataGridView. 
        With Me.DataGridView1.Rows
            .Add(New String() {"Starting Balance", "", "", "1000"})
            .Add(New String() {"Paycheck Deposit", "", "850", ""})
            .Add(New String() {"Rent", "-500", "", ""})
            .Add(New String() {"Groceries", "-25", "", ""})
            .Add(New String() {"Tax Return", "", "300", ""})
        End With 

        ' Allow the user to edit the starting balance cell
        DataGridView1.Rows(0).ReadOnly = True
        DataGridView1.Rows(0).Cells("Balance").ReadOnly = False 

        ' Autosize the columns. 
        Me.DataGridView1.AutoResizeColumns()

    End Sub 

    Private Sub CellValueChanged(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles DataGridView1.CellValueChanged

        ' Update the balance column whenever the values of any cell changes.
        UpdateBalance()
    End Sub 

    Private Sub RowsRemoved(ByVal sender As Object, _
        ByVal e As DataGridViewRowsRemovedEventArgs) _
        Handles DataGridView1.RowsRemoved

        ' Update the balance column whenever rows are deleted.
        UpdateBalance()
    End Sub 

    Private Sub UpdateBalance()
        Dim counter As Integer 
        Dim balance As Integer 
        Dim deposit As Integer 
        Dim withdrawal As Integer 

        ' Iterate through the rows, skipping the Starting Balance Row. 
        For counter = 1 To (DataGridView1.Rows.Count - 2)
            deposit = 0
            withdrawal = 0
            balance = Integer.Parse(DataGridView1.Rows(counter - 1) _
                .Cells("Balance").Value.ToString())

            If Not DataGridView1.Rows(counter) _
                .Cells("Deposits").Value Is Nothing Then 

                ' Verify that the cell value is not an empty string. 
                If Not DataGridView1.Rows(counter) _
                    .Cells("Deposits").Value.ToString().Length = 0 Then
                    deposit = Integer.Parse(DataGridView1.Rows(counter) _
                        .Cells("Deposits").Value.ToString())
                End If 
            End If 

            If Not DataGridView1.Rows(counter) _
                .Cells("Withdrawals").Value Is Nothing Then 
                If Not DataGridView1.Rows(counter) _
                    .Cells("Withdrawals").Value.ToString().Length = 0 Then
                    withdrawal = Integer.Parse(DataGridView1.Rows(counter) _
                        .Cells("Withdrawals").Value.ToString())
                End If 
            End If

            DataGridView1.Rows(counter).Cells("Balance").Value = _
                (balance + deposit + withdrawal).ToString()
        Next 
    End Sub 

    Private Sub SelectionChanged(ByVal sender As Object, _
        ByVal e As EventArgs) Handles DataGridView1.SelectionChanged

        ' Update the labels to reflect changes to the selection.
        UpdateLabelText()
    End Sub 

    Private Sub UserAddedRow(ByVal sender As Object, _
        ByVal e As DataGridViewRowEventArgs) _
        Handles DataGridView1.UserAddedRow

        ' Update the labels to reflect changes to the number of entries.
        UpdateLabelText()
    End Sub 

    Private Sub UpdateLabelText()
        Dim WithdrawalTotal As Integer = 0
        Dim DepositTotal As Integer = 0
        Dim SelectedCellTotal As Integer = 0
        Dim counter As Integer 

        ' Iterate through all the rows and sum up the appropriate columns. 
        For counter = 0 To (DataGridView1.Rows.Count - 1)
            If Not DataGridView1.Rows(counter) _
                .Cells("Withdrawals").Value Is Nothing Then 

                If Not DataGridView1.Rows(counter) _
                    .Cells("Withdrawals").Value.ToString().Length = 0 Then

                    WithdrawalTotal += _
                        Integer.Parse(DataGridView1.Rows(counter) _
                        .Cells("Withdrawals").Value.ToString())
                End If 
            End If 

            If Not DataGridView1.Rows(counter) _
                .Cells("Deposits").Value Is Nothing Then 

                If Not DataGridView1.Rows(counter) _
                    .Cells("Deposits").Value.ToString().Length = 0 Then

                    DepositTotal += _
                        Integer.Parse(DataGridView1.Rows(counter) _
                        .Cells("Deposits").Value.ToString())
                End If 
            End If 
        Next 

        ' Iterate through the SelectedCells collection and sum up the values. 
        For counter = 0 To (DataGridView1.SelectedCells.Count - 1)
            If DataGridView1.SelectedCells(counter).FormattedValueType Is _
            Type.GetType("System.String") Then 

                Dim value As String = Nothing 

                ' If the cell contains a value that has not been commited, 
                ' use the modified value. 
                If (DataGridView1.IsCurrentCellDirty = True) Then

                    value = DataGridView1.SelectedCells(counter) _
                        .EditedFormattedValue.ToString()
                Else

                    value = DataGridView1.SelectedCells(counter) _
                        .FormattedValue.ToString()
                End If 

                If value IsNot Nothing Then 

                    ' Ignore cells in the Description column. 
                    If Not DataGridView1.SelectedCells(counter).ColumnIndex = _
                        DataGridView1.Columns("Description").Index Then 

                        If Not value.Length = 0 Then
                            SelectedCellTotal += Integer.Parse(value)
                        End If 
                    End If 
                End If 
            End If 

        Next 

        ' Set the labels to reflect the current state of the DataGridView.
        Label1.Text = "Withdrawals Total: " & WithdrawalTotal.ToString()
        Label2.Text = "Deposits Total: " & DepositTotal.ToString()
        Label3.Text = "Selected Cells Total: " & SelectedCellTotal.ToString()
        Label4.Text = "Total entries: " & DataGridView1.RowCount.ToString()
    End Sub 

    Private Sub CellValidating(ByVal sender As Object, _
        ByVal e As DataGridViewCellValidatingEventArgs) _
        Handles DataGridView1.CellValidating

        Dim testInteger As Integer 

        If Not e.ColumnIndex = 0 Then 
            If Not e.FormattedValue.ToString().Length = 0 Then 

                ' Try to convert the cell value to an Integer. 
                If Not Integer.TryParse(e.FormattedValue.ToString(), _
                    testInteger) Then

                    DataGridView1.Rows(e.RowIndex).ErrorText = _
                        "Error: Invalid entry"

                    e.Cancel = True 
                End If 
            End If 
        End If 
    End Sub 

    Private Sub CellValidated(ByVal sender As Object, _
        ByVal e As DataGridViewCellEventArgs) _
        Handles DataGridView1.CellValidated

        ' Clear any error messages that may have been set in cell validation.
        DataGridView1.Rows(e.RowIndex).ErrorText = Nothing 
    End Sub 

    Private Sub UserDeletingRow(ByVal sender As Object, _
        ByVal e As DataGridViewRowCancelEventArgs) _
        Handles DataGridView1.UserDeletingRow

        Dim startingBalanceRow As DataGridViewRow = DataGridView1.Rows(0)

        ' Check if the starting balance row is included in the selected rows 
        If DataGridView1.SelectedRows.Contains(startingBalanceRow) Then 
            ' Do not allow the user to delete the Starting Balance row.
            MessageBox.Show("Cannot delete Starting Balance row!")

            ' Cancel the deletion if the Starting Balance row is included.
            e.Cancel = True 
        End If 
    End Sub 

End Class

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.