Monday, March 30, 2015

VB.net read text, write text, connect to SQL open connection query SQL and read results add to list box

Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO

Public Class Form1

    Public conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim i As Integer = 0
        Dim j As Integer = 0
        ListBox1.Items.Clear()
        If ListBox2.Items.Count > 0 Then
            For Each a As String In ListBox2.Items
                i = GetData(a)
                If i > 0 Then
                    j = j + 1
                End If
                ListBox1.Items.Add(String.Format("XYZ:{0} find:{1}", a, i))
                ListBox1.Refresh()
            Next
        End If
        MsgBox("done total found=" & j)
    End Sub

    Private Function GetData(ByVal xyz As Integer) As Integer
        Dim xyzLen As Integer = Len(xyz.ToString)
        Dim sql As String
        Dim xyzBackup As Integer
        xyzBackup = xyz
        If xyzLen = 6 Then
        ElseIf xyzLen < 9 Then
            xyz = Convert.ToInt32(OPERSCommon.Entity.XYZ.ConvertTDFinToSTFin(xyz))
        End If
        sql = "select FROM  where = " & xyz
        If conn.State = ConnectionState.Open Then
        Else
            conn.Open()
        End If
        Dim cnt As Integer = 0
        Dim cmd As New Data.SqlClient.SqlCommand(sql, conn)
        Try

            Dim dr As SqlDataReader = cmd.ExecuteReader()
            While (dr.Read())
                cnt = cnt + 1
            End While
        Catch ex As Exception
            MessageBox.Show("SQL conn error" & ex.Message)
        End Try
        cmd.Dispose()
        conn.Close()
        If cnt > 0 Then
            ListBox3.Items.Add(String.Format("before XYZ={0}=>{1}={2}", xyzBackup, xyz, cnt))
            ListBox3.Refresh()
            Dim lineout As String = xyzBackup & " " & xyz
            Using sw As StreamWriter = New StreamWriter("c:\XYZOnProdandTest.txt", True)
                sw.WriteLine(lineout)
            End Using
        End If
        Return cnt
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        For Each line As String In File.ReadLines("c:\XYZFromMSBSDB2P.txt")
            ListBox2.Items.Add(line)
        Next
    End Sub
End Class


No comments:

Post a Comment