VB.NET備忘録

#####リソースの使用

１、［Myproject］→［リソース］でリソースを追加する

２、コードで制御する

```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PictureBox1.Image = My.Resources.Image1
        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
    End Sub
```

#####名前空間の参照

［MyProject］→［参照］で参照設定

※参照することでSystem.IOを省略できる！

```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Directory.Exists(TextBox1.Text) Then
            Label1.Text = "発見！"
        Else
            Label1.Text = "ないです"
        End If
    End Sub
```

#####変数の定義
```
Dim a As String
a = "hello"
Dim x As Integer = 1000
Dim weight As Single, height As Single
```

#####リテラル値のデータ型
```
Dim x1 = 100I     'integer型
Dim x2 = 100.0F   'single型
```

#####Null許容型
```
Dim x1 As Nullable(Of Integer)
Dim x2 As Integer?
```

#####定数
```
Const APPLI As String = "Visual Basic"
Const TIPS_NUM As Integer = 1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Const STR As String = "の学習"
    Label1.Text = APPLI & STR & TIPS_NUM
End Sub
```
#####列挙型
```
Public Class Form1

    Private Enum ClassType
        special      '0
        standard     '1
        basic        '2
    End Enum

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

        Select Case ComboBox1.SelectedItem
            Case CInt(ClassType.special)
                test = ClassType.special
            Case CInt(ClassType.standard)
                test = ClassType.standard
            Case CInt(ClassType.basic)
                test = ClassType.basic
        End Select
        Label1.Text = test.ToString()
    End Sub
End Class
```
※列挙型はメソッド内で宣言できない。
※１つのメンバーの値を指定したとき、次のメンバーにはその値に１を加えた値が自動的に設定される。

#####データ型を変換
```
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer = 30
    Dim lng As Long = i     '暗黙の型変換
    Dim d As Double = 123.456
    i = CInt(d)             'キャスト（桁落ち）
    Label1.Text = i
    Dim o As Object = i     '暗黙の型変換
    o = "VISUAL BASIC 2017"
    Dim s1 As String = DirectCast(o, String)
    Dim s2 As String = TryCast(o, String)
End Sub
```
```
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim d As Double
    d = Double.Parse(TextBox1.Text)
    Me.Label1.Text = d.ToString()
End Sub
```

#####メッセージボックス
```
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim ret = MessageBox.Show("ボタンをクリックしてください", "通知",
                                  MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

    Select Case ret
        Case DialogResult.Yes
             Label1.Text = "[はい]がクリックされました"
        Case DialogResult.No
             Label1.Text = "[いいえ]がクリックされました"
        Case DialogResult.Cancel
             Label1.Text = "[キャンセル]がクリックされました"
    End Select
End Sub
```

#####改行やタブの挿入
```
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
     Dim s1 As String = "ワイン"
     Dim s2 As String = "チーズ"
     Label1.Text = "C:\VB2017\Sample.txt"
     Label2.Text = """C:\VB2017\Sample.txt"""
     Label3.Text = s1 & ControlChars.Lf & s2
     Label4.Text = $"{s1}{ControlChars.Lf}{s2}"
End Sub
```

#####Object型
```
Public Class Form1

    Private Function sampleMethod(x As Object) As Object
        If TypeOf x Is String Then
            Return 365
        Else
            Return "文字列を返す"
        End If
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim o As Object
        o = sampleMethod("SAMPLE")
        Label1.Text = o.ToString()
        o = sampleMethod(15)
        Label2.Text = o.ToString()
    End Sub
End Class
```

#####プログラムの終了
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ret = MessageBox.Show("アプリケーションを終了しますか？", "確認",
                                  MessageBoxButtons.YesNo)

        If ret = DialogResult.Yes Then
            Application.Exit()
        End If
    End Sub
```

#####加減乗除
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim X As Integer = 100
        Label1.Text = (X / 20).ToString()
        X += 20
        Label2.Text = X.ToString()
    End Sub
```

#####複数条件の判断
```
Public Class Form1

    Private Function Check1()
        Label2.Text += " Check1呼び出し"
        Return CheckBox1.Checked
    End Function

    Private Function Check2()
        Label2.Text += " Check2呼び出し"
        Return CheckBox2.Checked
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label2.Text = ""
        Dim ret = Check1() And Check2()
        Label1.Text = "And演算子の結果：" + ret.ToString()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Label2.Text = ""
        Dim ret = Check1() AndAlso Check2()
        Label1.Text = "AndAlso演算子の結果：" + ret.ToString()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Label2.Text = ""
        Dim ret = Check1() Or Check2()
        Label1.Text = "Or演算子の結果：" + ret.ToString()
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Label2.Text = ""
        Dim ret = Check1() OrElse Check2()
        Label1.Text = "OrElse演算子の結果：" + ret.ToString()
    End Sub
End Class
```

#####型のキャストが可能か調べる
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For Each o As Control In Controls
            If TypeOf o Is CheckBox Then
                o.Text = "clicked!"
            End If
        Next
    End Sub
```

#####絶対値
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim x As Integer = -1234
        MessageBox.Show(x & "の絶対値：" & Math.Abs(x).ToString, "確認")
    End Sub
```

#####平方根
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim x As Double = 3.0
        MessageBox.Show(x & "の平方根" & Math.Sqrt(x).ToString, "確認")
    End Sub
```

#####乱数
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim rnd = New Random()
        Label1.Text = rnd.Next(100)
        Label2.Text = rnd.Next(100, 1001)
    End Sub
```

#####現在の日付と時刻取得
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DateTime.Now
        'xxxx年xx月xx日   xxxx/xx/xx
        Label1.Text = dt.ToLongDateString() & vbNewLine & dt.ToShortDateString
        'xx:xx:xx    xx:xx
        Label2.Text = dt.ToLongTimeString() & vbNewLine & dt.ToShortTimeString
        Label3.Text = dt.ToString()
    End Sub
```

#####日付要素取得
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DateTime.Now
        Label1.Text = dt.Year
        Label2.Text = dt.Month
        Label3.Text = dt.Day
    End Sub
```

#####曜日取得
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DateTime.Today
        Select Case dt.DayOfWeek
            Case DayOfWeek.Sunday
                Label1.Text = "日曜日"
            Case DayOfWeek.Monday
                Label1.Text = "月曜日"
            Case DayOfWeek.Tuesday
                Label1.Text = "火曜日"
            Case DayOfWeek.Wednesday
                Label1.Text = "水曜日"
            Case DayOfWeek.Thursday
                Label1.Text = "木曜日"
            Case DayOfWeek.Friday
                Label1.Text = "金曜日"
            Case DayOfWeek.Saturday
                Label1.Text = "土曜日"
        End Select
    End Sub
```

#####一定期間前や後の日付、時刻を求める
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DateTime.Now
        Label1.Text = dt
        Label2.Text = dt.AddHours(-5)
        Label3.Text = dt.AddDays(10)
    End Sub
```

#####2つの日時の間隔を求める
```
Public Class Form1
    Private sTime As DateTime
    Private eTime As DateTime

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        sTime = DateTime.Now
        Label1.Text = ""
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        eTime = DateTime.Now
        Dim ts = eTime.Subtract(sTime)  'TimeSpan型

        If ts.Seconds = 10 Then
            Label1.Text = "おめでとう　" & ts.TotalSeconds.ToString("##.##")
        Else
            Label1.Text = "残念" & ts.TotalSeconds.ToString("##.##")
        End If
    End Sub
End Class
```

#####任意の時間間隔を作成
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ts1 = New TimeSpan(20, 10, 5)         '20時間10分5秒
        Dim ts2 = New TimeSpan(0, 25, 20, 15)     '0日25時間20分15秒
        Dim ts3 = New TimeSpan(0, 0, 0, 0, 1001)  '0秒1001ミリ秒
        Label1.Text = ts1.ToString()
        Label2.Text = ts2.ToString()
        Label3.Text = ts3.ToString()
    End Sub
```

#####任意の日付を作成
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt1 = New DateTime(2018, 2, 25)
        Dim dt2 = New DateTime(2018, 5, 1, 12, 34, 56)
        Label1.Text = dt1.ToString()
        Label2.Text = dt2.ToString()
    End Sub
```

#####現在の月の日数を取得
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
    End Sub
```

#####日付文字列を日付データにする
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt As DateTime
        Dim ret = DateTime.TryParse(TextBox1.Text, dt)
        If ret Then
            Label1.Text = dt
        Else
            Label1.Text = "変換不可"
        End If
    End Sub
```

#####ifステートメント
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt As DateTime

        If TextBox1.Text = "" Then
            Label1.Text = "入力されていません"
        ElseIf DateTime.TryParse(TextBox1.Text, dt) Then
            Label1.Text = "入力した日付：" & dt
        Else
            Label1.Text = "正しい日付を入力してください"
        End If
    End Sub
```

#####selectステートメント
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Select Case ComboBox1.Text
            Case "オレンジ"
                BackColor = Color.Orange
            Case "ブルー"
                BackColor = Color.Blue
            Case "イエロー"
                BackColor = Color.Yellow
            Case Else
                BackColor = Color.Empty
        End Select
    End Sub
```

#####forステートメント
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.Items.Clear()
        For i = 1 To 10
            ListBox1.Items.Add("No." & i)
        Next
    End Sub
```

#####whileステートメント
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim i As Integer = 1
        ListBox1.Items.Clear()
        While i < 11
            ListBox1.Items.Add("No." & i)
            i += 1
        End While
    End Sub
```

#####doステートメント
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim i = 11
        ListBox1.Items.Clear()
        Do
            ListBox1.Items.Add("No." & i)
            i += 1
        Loop While i <= 10
    End Sub
```

#####配列の処理の繰り返し
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str = ""

        For Each chk As CheckBox In GroupBox1.controls
            If chk.Checked = True Then
                str += chk.Text & ControlChars.Tab
            End If
        Next

        If str <> "" Then
            MessageBox.Show(str & ControlChars.Lf & "が選ばれました", "確認")
        End If
    End Sub
```

#####ループの途中で処理を先頭に戻す
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str1 = ""
        Dim str2 = ""
        For Each chk As RadioButton In GroupBox1.Controls
            If chk.Checked = True Then
                str1 += chk.Text & " "
                Continue For
            Else
                str2 += chk.Text & ""
            End If
        Next

        If str1 <> "" Then
            MessageBox.Show(str1 & vbLf & "が選択されました" & vbLf &
                            str2 & vbLf & "が選択されませんでした", "確認")
        End If
    End Sub
```

#####if関数
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DateTime.Today
        Dim RetStr = If(dt.Day <= 15, "前半", "後半")
        Label1.Text = $"今日の日付：{dt}" & ControlChars.Lf &
            $"月の{RetStr}です。"
    End Sub
```

#####配列
```Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ary = New Integer(4) {}
        Label1.Text = ""
        For i As Integer = 0 To 4
            ary(i) = i * 2
            Label1.Text += $"ary[{i}] = {ary(i)}" & ControlChars.Lf
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim ary = New Integer(1, 2) {}
        Label1.Text = ""
        For i As Integer = 0 To 1
            For j As Integer = 0 To 2
                ary(i, j) = i + j
                Label1.Text += $"ary[{i},{j}] = {ary(i, j)}"
            Next
            Label1.Text += ControlChars.Lf
        Next
    End Sub
End Class
```

#####配列の宣言時に値入れる
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim names As String() = {"田中", "佐藤", "高橋", "伊藤", "清水"}
        Dim i As Integer
        If ComboBox1.SelectedIndex = -1 Then
            Label1.Text = "クラスを選択してください"
            Return
        End If
        i = ComboBox1.SelectedIndex
        Label1.Text = ComboBox1.SelectedItem + $"組の担任：{names(i)}先生"
    End Sub
```

#####配列の要素数を求める
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Xary = New Integer(4) {}
        Dim yAry = New Integer(1, 2) {}
        Label1.Text = $"xAry(4)の要素数：{Xary.Length}"
        Label2.Text = $"yAry(1,2)の全要素数：{yAry.Length}" & vbLf &
            $"一つ目の要素数：{yAry.GetLength(0)}" & vbLf &
            $"二つ目の要素数：{yAry.GetLength(1)}"
    End Sub
```

#####配列の要素数を変更
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ary = New String() {"東京", "名古屋", "大阪"}
        Label1.Text = "配列aryの要素数：" & ary.Length & vbLf
        Label1.Text &= $"ary(0)={ary(0)},ary(1)={ary(1)},ary(2)={ary(2)}"
        ary = New String(4) {}
        Label2.Text = "配列aryの要素数：" & ary.Length & vbLf
        Label2.Text &= $"ary(0)={ary(0)},ary(1)={ary(1)},ary(2)={ary(2)}"
    End Sub
```

#####ジャグ配列
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim student = New Integer(2)() {}
        student(0) = New Integer(2) {37, 35, 34}
        student(1) = New Integer(1) {41, 43}
        student(2) = New Integer(3) {33, 34, 33, 35}
        ListBox1.Items.Clear()
        For i = 0 To student.Length - 1
            ListBox1.Items.Add($"{i + 1}年")
            For j = 0 To student(i).Length - 1
                ListBox1.Items.Add($" {j + 1}組：{student(i)(j)}")
            Next
        Next
    End Sub
```

#####配列の要素並べ替え
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim apli = New String() {"PowerPoint", "Excel", "Word", "Access"}

        ListBox1.Items.Clear()
        ListBox2.Items.Clear()
        ListBox3.Items.Clear()

        ListBox1.Items.AddRange(apli)
        Array.Sort(apli)
        ListBox2.Items.AddRange(apli)
        Array.Reverse(apli)
        ListBox3.Items.AddRange(apli)

    End Sub
```

#####配列をクリア
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ary = New String() {"東京", "名古屋", "大阪"}
        Label1.Text = $"ary(0)={ary(0)},ary(1)={ary(1)},ary(2)={ary(2)}"
        Array.Clear(ary, 1, 2)
        Label2.Text = $"ary(0)={ary(0)},ary(1)={ary(1)},ary(2)={ary(2)}"
    End Sub
```

#####配列をコピー
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ary1 = {10, 20, 30}
        Dim ary2 = {6, 7, 8, 9, 0}
        Dim ary3 = ary1.Clone()
        Dim ary4 = ary1

        ary1.CopyTo(ary2, 2)
        ary1(0) = 99
        Label1.Text = "ary1 = "
        Label2.Text = "ary2 = "
        Label3.Text = "ary3 = "
        Label4.Text = "ary4 = "

        For i = 0 To ary1.Length - 1
            Label1.Text += ary1(i) & " "
        Next

        For i = 0 To ary2.Length - 1
            Label2.Text += ary2(i) & " "
        Next

        For i = 0 To ary3.Length - 1
            Label3.Text += ary3(i) & " "
        Next

        For i = 0 To ary4.Length - 1
            Label4.Text += ary4(i) & " "
        Next
    End Sub
```

#####ArrayListクラス(可変長)
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New ArrayList()
        lst.AddRange(ListBox1.Items)
        Label1.Text = "最初の要素：" & lst(0)
        Label2.Text = "要素数：" & lst.Count
    End Sub
```

#####Listジェネリッククラス（型指定）
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New List(Of String)()
        lst.AddRange(New String() {"味噌", "醤油", "お酢"})
        Label1.Text = ""
        For i As Integer = 0 To lst.Count - 1
            Label1.Text += lst(i) + ControlChars.Lf
        Next
    End Sub
```

#####Listジェネリッククラスの要素並べ替え
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New List(Of String)() From {
        "いちご",
        "メロン",
        "スイカ",
        "ぶどう"
        }
        ListBox1.Items.Clear()
        ListBox2.Items.Clear()
        ListBox3.Items.Clear()
        ListBox1.Items.AddRange(lst.ToArray()) 'ToArrayはリストを配列に変換
        lst.Sort()
        ListBox2.Items.AddRange(lst.ToArray())
        lst.Reverse()
        ListBox3.Items.AddRange(lst.ToArray())
    End Sub
```

#####コレクションの要素から値を検索
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New List(Of String)() From {
        "東京",
        "品川",
        "新横浜"
        }

        For Each val As Object In ListBox1.Items
            lst.Add(val)
        Next

        Dim ret As Integer = lst.IndexOf(TextBox1.Text)
        If ret = -1 Then
            Label1.Text = "コレクション内に存在しません"
        Else
            Label1.Text = TextBox1.Text & "のインデックス：" & ret
        End If

    End Sub
```

#####Dictionaryジェネリッククラス
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dic = New Dictionary(Of String, String)
        dic("ex") = "Excel"
        dic("pp") = "PowerPoint"
        dic.Add("wd", "Word")
        dic.Add("ac", "Access")
        Label1.Text = dic("wd")
        ListBox1.Items.Clear()
        For Each myKey As String In dic.Keys
            ListBox1.Items.Add(myKey)
        Next
        ListBox2.Items.Clear()
        For Each myVal As String In dic.Values
            ListBox2.Items.Add(myVal)
        Next
        ListBox3.Items.Clear()
        For Each myPair In dic
            ListBox3.Items.Add(myPair.Key & ControlChars.Tab & myPair.Value)
        Next
    End Sub
```

#####SortedListジェネリッククラス（キーでソートした型指定コレクション）
```
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New SortedList(Of String, String)
        lst("vb") = "Visual Basic"
        lst("pp") = "Power Point"
        lst.Add("wd", "Word")
        lst.Add("ac", "Access")
        ListBox1.Items.Clear()
        Dim i = 0
        For Each it In lst
            ListBox1.Items.Add($"{i}：{it.Key}：{it.Value}")
            i += 1
        Next
        lst.Add("ex", "Excel")
        ListBox2.Items.Clear()
        i = 0
        For Each it In lst
            ListBox2.Items.Add($"{i}：{it.Key}：{it.Value}")
            i += 1
        Next
    End Sub
```

#####コレクションから条件にマッチした要素を取り出す
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lst = New List(Of MyItem)()
        lst.Add(New MyItem With {.Key = "vb", .Text = "VisualBasic"})
        lst.Add(New MyItem With {.Key = "pp", .Text = "PowerPoint"})
        lst.Add(New MyItem With {.Key = "wd", .Text = "Word"})
        lst.Add(New MyItem With {.Key = "ac", .Text = "Access"})
        ListBox1.Items.Clear()
        For Each it In lst
            ListBox1.Items.Add($"{it.Key}：{it.Text}")
        Next
        Dim item = lst.FirstOrDefault(Function(x)
                                          Return x.Key = TextBox1.Text
                                      End Function)

        If item Is Nothing Then
            Label1.Text = "なし"
        Else
            Label1.Text = item.Text
        End If
    End Sub

End Class

Public Class MyItem
    Public Property Key As String
    Public Property Text As String
End Class
```

#####subメソッド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xStr As String = "Param"
        Dim yStr As String = "Param"
        xProc(xStr)
        yProc(yStr)
        Label1.Text = Convert.ToString("値渡しの結果：") & xStr
        Label2.Text = Convert.ToString("参照渡しの結果：") & yStr
    End Sub

    Private Sub xProc(ByVal xParam As String)
        xParam = "Change!"
    End Sub

    Private Sub yProc(ByRef yParam As String)
        yParam = "Change!"
    End Sub

End Class
```

#####functionメソッド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ret = proc(10, 20)
        Label1.Text = "取得した戻り値：" & ret.ToString()
    End Sub

    Private Function proc(x As Integer, y As Integer) As Integer
        Return x * y
    End Function

End Class
```

#####配列を受け渡すメソッド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim lstX = {"London", "Paris", "NewYork"}
        Dim lstY = proc(lstX)

        Label2.Text = ""
        For Each city As String In lstY
            Label2.Text += city & ControlChars.Lf
        Next

    End Sub

    Private Function proc(lst As String()) As String()
        Label1.Text = ""
        For Each city In lst
            Label1.Text += city & ControlChars.Lf
        Next
        lst(2) = "tokyo"
        Return lst
    End Function

End Class
```

#####引数の数が可変のメソッド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        proc(True)
        proc(False, "数学")
        proc(False, "国語", "社会")
    End Sub

    Private Sub proc(result As Boolean, ParamArray kamoku As String())
        Dim gouhi As String = "合格"
        If result = False Then
            gouhi = "追試-->"
        End If
        For Each item As String In kamoku
            gouhi += " " & item
        Next
        MessageBox.Show($"期末試験の結果　：　{gouhi}", "確認")
    End Sub

End Class
```

#####オーバーロード
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        proc("1月")
        proc(2)

    End Sub

    Private Sub proc(nextMonth As String)
        MessageBox.Show("次回の放送は　" & nextMonth & "　です", "通知")
    End Sub

    Private Sub proc(nextMonth As Integer)
        proc(nextMonth & "月")
    End Sub

End Class
```

#####クラスのコンストラクター作成
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim obj = New SampleClass("新規お客様")
        MessageBox.Show("インスタンス生成", "確認")
    End Sub
End Class

Public Class SampleClass
    Private _name As String
    Private _id As String
    Public Sub New(Name As String)
        _name = Name
        _id = DateTime.Now.ToString("yyyyMMddHHmm")
    End Sub
End Class
```

#####クラスのプロパティ
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim o = New SampleClass("新規お客様")
        o.Name = "やまだはなこ"
        MessageBox.Show($"Name:{o.Name}", "確認")
    End Sub
End Class

Public Class SampleClass
    Private _name As String

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(value As String)
            _name = value
        End Set
    End Property

    Public Sub New(Name As String)
        _name = Name
    End Sub

End Class
```

#####自動実装プロパティ
```
Public Class SampleClass
    Public Property Name As String

    Public Sub New(Name As String)
        _name = Name
    End Sub
End Class
```

#####クラスのメソッド定義
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim o = New SampleClass("新規お客様")
        o.ShowData()
        MessageBox.Show("氏名：" & o.GetName("山田花子様"), "確認")
    End Sub
End Class

Public Class SampleClass
    Private _name As String

    Public Sub ShowData()
        MessageBox.Show("お客様名：" & _name, "確認")
    End Sub

    Public Function GetName(name As String) As String
        If name.EndsWith("様") Then
            Return name.Substring(0, name.Length - 1)
        Else
            Return name
        End If
    End Function

    Public Sub New(Name As String)
        _name = Name
    End Sub
End Class
```

#####クラスのイベント定義
```
Public Class SampleClass
    Public Event MyEvent As Action(Of Object, EventArgs)
    Public Event ev As EventHandler
    Public Sub MyMethod()
        Dim msg As String = DateTime.Now.ToString("HH:mm:ss")
        RaiseEvent MyEvent(Me, EventArgs.Empty)
    End Sub
End Class
```

#####イベントハンドラー作成
```
Public Class Form1
    Private o As New SampleClass

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler o.MyEvent, AddressOf o_MyEvent
    End Sub

    Private Sub o_MyEvent(s As String)
        Label1.Text = s
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        o.proc()
    End Sub
End Class

Public Class SampleClass
    Public Event MyEvent As Action(Of String)
    Public Sub proc()
        Dim msg As String = DateTime.Now.ToString("HH:mm:ss")
        RaiseEvent MyEvent(msg)
    End Sub
End Class
```

#####オブジェクト生成時にプロパティ設定
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim o As New SampleClass() With {
            .Name = "やまだはなこ"
        }
    End Sub
End Class

Public Class SampleClass
    Public Property Name As String
End Class
```

#####クラスの継承
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim tel = New SampleClassTel("山田花子", "123456789")
        MessageBox.Show($"名前：　{tel.Name}", "派生クラス")
    End Sub
End Class

Public Class SampleClass
    Public ReadOnly Property Name As String
    Public Property Id As String
    Public Sub New(name As String)
        Me.Name = name
        Me.Id = DateTime.Now.ToString("yymmddhhmm")
    End Sub
End Class

Public Class SampleClassTel
    Inherits SampleClass
    Public ReadOnly Property Tel As String
    Public Sub New(name As String, tel As String)
        MyBase.New(name)
        Me.Tel = tel
    End Sub
End Class
```

#####派生クラスで再定義
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim tel = New SampleClassTel("山田花子", "123456789")
        tel.ShowData()
    End Sub
End Class

Public Class SampleClass
    Public Property Name As String
    Public Property Id As String
    Public Sub New(name As String)
        Me.Name = name
        Me.Id = DateTime.Now.ToString("yymmddhhmm")
    End Sub
    Public Overridable Sub ShowData()
        MessageBox.Show($"お客様氏名：{Id}-{Name}", "確認")
    End Sub
End Class

Public Class SampleClassTel
    Inherits SampleClass
    Public ReadOnly Property Tel As String
    Public Sub New(name As String, tel As String)
        MyBase.New(name)
        Me.Tel = tel
    End Sub
    Public Overrides Sub ShowData()
        MyBase.ShowData()
        MessageBox.Show($"お客様電話番号：{Tel}", "確認")
    End Sub
End Class
```

#####型情報を引数にするクラス
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim genericStr = New MyGeneric(Of String)() With {
            .Value = "Visual Basic"
            }
        Dim genericInt = New MyGeneric(Of Integer)() With {
            .Value = 2017
            }
        MessageBox.Show(genericStr.Value & " " & genericInt.Value, "確認")
    End Sub
End Class

Public Class MyGeneric(Of T)
    Private _val As T
    Public Property Value() As T
        Get
            Return _val
        End Get
        Set(value As T)
            _val = value
        End Set
    End Property
End Class
```

#####構造体の定義
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim mn As MyMenu
        mn.menuNo = 1
        mn.Menu = "みそラーメン"
        mn.price = 750
        MessageBox.Show("大盛価格->\" & mn.priceBig, mn.Menu)
    End Sub
End Class

Public Structure MyMenu
    Public menuNo As Integer
    Public Menu As String
    Public price As Integer
    Public ReadOnly Property priceBig() As Integer
        Get
            Return price + 100
        End Get
    End Property
End Structure
```

#####構造体配列
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim mc = New MyStruct(2) {}
        ListBox1.Items.Clear()
        For i As Integer = 0 To 2
            mc(i).CourseNo = (i + 1).ToString("00")
            mc(i).CourseName = "コース名未定"
            mc(i).Num = 20
            ListBox1.Items.Add(
                $"{mc(i).CourseNo}-{mc(i).CourseName}-{mc(i).Num}名")
        Next
    End Sub
End Class

Public Structure MyStruct
    Public CourseNo As String
    Public CourseName As String
    Public Num As Integer
End Structure
```

#####構造体や配列を構造体のメンバーにする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim bs As BurgerSet
        Dim setSize = {"S", "M", "L"}
        bs.Burger = "チーズバーガー"
        bs.Drink.Name = "コーラ"
        bs.Drink.Size = setSize
        MessageBox.Show(bs.Burger & vbLf &
                        bs.Drink.Name & vbLf &
                        bs.Drink.Size(1), "確認")
    End Sub
End Class

Public Structure BurgerSet
    Public Drink As Drink
    Public Burger As String
End Structure

Public Structure Drink
    Public Name As String
    Public Size As String()
End Structure
```

#####構造体を受け取るメソッド
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim mn As StructMenu
        mn.MenuNo = 1
        mn.Menu = "味噌ラーメン"
        mn.Price = 750
        showData(mn)
    End Sub

    Private Sub showData(nMenu As StructMenu)
        MessageBox.Show(nMenu.Menu & ":" & nMenu.Price.ToString("0円"), "確認")
    End Sub
End Class

Public Structure StructMenu
    Public MenuNo As Integer
    Public Menu As String
    Public Price As Integer
End Structure
```

#####構造体を返すメソッド
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pt As Point
        pt = twicePoint(100, 200)
        MessageBox.Show(pt.x & " " & pt.y, "戻り値")
    End Sub

    Public Function twicePoint(x As Integer, y As Integer) As Point
        Dim pt As Point
        pt.x = x * 2
        pt.y = y * 2
        Return pt
    End Function
End Class

Public Structure Point
    Public x As Integer
    Public y As Integer
End Structure
```

#####タスクの作成
```
Public Class Form1
    Private _task As Task

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        _task = New Task(
            Sub()
                For i As Integer = 0 To 59
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text =
                                  DateTime.Now.ToString("HH:MM:ss")
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
            End Sub)
        _task.Start()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        _task = New Task(AddressOf OnWork)
        _task.Start()
    End Sub

    Private Sub OnWork()
        For i As Integer = 0 To 59
            Me.Invoke(New Action(Sub()
                                     Label1.Text =
                                     DateTime.Now.ToString("HH:MM:mm")
                                 End Sub))
            System.Threading.Thread.Sleep(1000)
        Next
    End Sub
End Class
```

#####タスクを作成して実行
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Await Task.Factory.StartNew(
        Sub()
            For i As Integer = 0 To 59
                Me.Invoke(New Action(Sub()
                                         Label1.Text =
                                         DateTime.Now.ToString("HH:MM:ss")
                                     End Sub))
                System.Threading.Thread.Sleep(1000)
            Next
        End Sub)
    End Sub

    Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim task1 As New Task(
            Sub()
                For i As Integer = 0 To 59
                    Me.Invoke(New Action(Sub()
                                             Label1.Text =
                                             DateTime.Now.ToString("HH:MM:ss")
                                         End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
            End Sub)
        Await Task.Delay(5000)
        task1.Start()
    End Sub

End Class
```

#####戻り値を持つタスク
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ret = Await Task.Factory.StartNew(
            Function()
                Dim i = 0
                While i < 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text =
                                  $"{i}秒経過"
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                    i = i + 1
                End While
                Return DateTime.Now
            End Function)
        Label1.Text = & "最終時刻：{ret}"
    End Sub

End Class
```

#####タスクの完了を待つ
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Await Task.Run(Sub() onTask1())
        Await Task.Run(Sub() onTask2())
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Task.Run(Sub() onTask1())
        Task.Run(Sub() onTask2())
    End Sub

    Private Sub onTask1()
        Dim i = 0
        While i < 10
            Me.Invoke(New Action(
                      Sub()
                          Label1.Text = $"{i}秒経過"
                      End Sub))
            System.Threading.Thread.Sleep(1000)
            i = i + 1
        End While
    End Sub

    Private Sub onTask2()
        Dim i = 0
        While i < 10
            Me.Invoke(New Action(
                      Sub()
                          Label2.Text = $"{i}秒経過"
                      End Sub))
            System.Threading.Thread.Sleep(1000)
            i = i + 1
        End While
    End Sub

End Class
```

#####複数のタスクの実行を待つ
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Task.Factory.StartNew(
            Sub()
                Me.Invoke(New Action(
                          Sub()
                              Label3.Text = "タスク開始"
                          End Sub))
                Dim task1 = Task.Factory.StartNew(Sub() onTask1())
                Dim task2 = Task.Factory.StartNew(Sub() onTask2())
                Task.WaitAll(task1, task2)
                Me.Invoke(New Action(
                          Sub()
                              Label3.Text = "タスク終了"
                          End Sub))
            End Sub)
    End Sub

    Private Sub onTask1()
        Dim i = 0
        While i < 5
            Me.Invoke(New Action(
                      Sub()
                          Label1.Text = $"{i}秒経過"
                      End Sub))
            System.Threading.Thread.Sleep(1000)
            i = i + 1
        End While
    End Sub

    Private Sub onTask2()
        Dim i = 0
        While i < 10
            Me.Invoke(New Action(
                      Sub()
                          Label2.Text = $"{i}秒経過"
                      End Sub))
            System.Threading.Thread.Sleep(1000)
            i = i + 1
        End While
    End Sub

End Class
```

#####非同期メソッドの呼び出し
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sum As Integer = Await onWork()
        MessageBox.Show($"合計値 {sum}")
    End Sub

    Private Function onWork() As Task(Of Integer)
        Dim task = New Task(Of Integer)(
            Function()
                Dim sum As Integer
                For i As Integer = 1 To 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒経過"
                              End Sub))
                    sum += 1
                    System.Threading.Thread.Sleep(1000)
                Next
                Return sum
            End Function)
        task.Start()
        Return task
    End Function

End Class
```

#####タスクの終了時に実行を継続する
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Await onWork()
    End Sub

    Private Function onWork() As Task(Of Integer)
        Dim task = New Task(Of Integer)(
            Function()
                Dim sum As Integer = 0
                For i As Integer = 1 To 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒追加"
                              End Sub))
                    sum += i
                    System.Threading.Thread.Sleep(1000)
                Next
                Return sum
            End Function)
        task.Start()
        task.ContinueWith(
            Sub(t)
                Dim res As Integer = t.Result
                Me.Invoke(New Action(
                          Sub()
                              Label2.Text = $"合計値：{res}"
                          End Sub))
            End Sub)
        Return task
    End Function

End Class
```

#####スレッドを切り替えてUI変更
```
Public Class Form1

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = 10
        Await Task.Factory.StartNew(
            Sub()
                Dim i As Integer
                For i = 1 To 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = String.Format("{0}秒経過", i)
                              End Sub))
                    Me.Invoke(New Action(
                              Sub()
                                  ProgressBar1.Value = i
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
            End Sub)
        MessageBox.Show("10秒経過しました")
    End Sub

End Class
```

#####一定時間停止する
```
Public Class Form1

    'Sleepメソッド
    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Await Task.Factory.StartNew(
            Sub()
                Dim i As Integer
                For i = 1 To 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒経過"
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
            End Sub)
        Label1.Text = "10秒経過"
    End Sub

    'Delayメソッド
    Private Async Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Await Task.Factory.StartNew(
            Async Function()
                Dim i As Integer
                For i = 1 To 10
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒経過"
                              End Sub))
                    Await Task.Delay(1000)
                Next
            End Function)
        Label1.Text = "10秒経過"
    End Sub
End Class
```

#####イベントが発生するまで停止
```
Public Class Form1

    Private mre As System.Threading.ManualResetEvent

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        mre = New System.Threading.ManualResetEvent(False)
        Await Task.Factory.StartNew(
            Sub()
                Dim i As Integer
                For i = 1 To 20
                    If i = 10 Then
                        Me.Invoke(New Action(
                                  Sub()
                                      Label1.Text = "解除イベント待ち"
                                  End Sub))
                        mre.Reset()
                        mre.WaitOne()
                    End If
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒経過"
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
            End Sub)
        Label1.Text = "タスク終了"
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        mre.Set()
    End Sub
End Class
```

#####タスクの実行キャンセル
```
Public Class Form1

    Private cts As New System.Threading.CancellationTokenSource()

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim res = Await Task.Factory.StartNew(Of Boolean)(
            Function()
                Dim i As Integer
                For i = 1 To 10
                    If cts.Token.IsCancellationRequested Then
                        Return False
                    End If
                    Me.Invoke(New Action(
                              Sub()
                                  Label1.Text = $"{i}秒経過"
                              End Sub))
                    System.Threading.Thread.Sleep(1000)
                Next
                Return True
            End Function, cts.Token)
        If res Then
            Label1.Text = "タスク正常終了"
        Else
            Label1.Text = "タスクがキャンセルされました"
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        cts.Cancel()
    End Sub
End Class
```

###DB操作

#####IDEにDB接続
[表示]->[サーバーエクスプローラー]->[データ接続]右クリック->[接続の追加]

#####プロジェクトにDB接続
[プロジェクト]->[新しいデータソースの追加]

#####実行時DB接続
※System.sqlClient、System.Configurationを参照設定する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cs As String = ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString
        Dim cn As SqlConnection = New SqlConnection(cs)
        Try
            cn.Open()
            MessageBox.Show("接続しました", "通知")
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データベースの接続状況取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            MessageBox.Show($"接続状態：{cn.State}", "通知")
            cn.Close()
            MessageBox.Show($"接続状態：{cn.State}", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブル名の一覧表示
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim schemaTable As DataTable = cn.GetSchema("Tables")
            cn.Close()
            ListBox1.Items.Clear()
            For Each dr As DataRow In schemaTable.Rows
                ListBox1.Items.Add(dr(2))
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルのフィールド一覧を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim dt As DataTable = cn.GetSchema("Columns")
            cn.Close()
            ListBox1.Items.Clear()
            For i As Integer = 0 To dt.Rows.Count - 1
                ListBox1.Items.Add(dt.Rows(i)("COLUMN_NAME").ToString())
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データベースに神機テーブル追加
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "drop table テスト"
            Dim cm = New SqlCommand(sql, cn)
            cm.ExecuteNonQuery()
            MessageBox.Show("テーブル削除", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルにレコード追加
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "insert into 社員 values('100091','たなかはなこ','01')"
            Dim cm = New SqlCommand(sql, cn)
            cm.ExecuteNonQuery()
            MessageBox.Show("追加", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルのレコード削除
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "delete from 社員 where 社員番号 = 100091"
            Dim cm = New SqlCommand(sql, cn)
            cm.ExecuteNonQuery()
            MessageBox.Show("削除", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルのレコード参照
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "select * from 社員"
            Dim cm = New SqlCommand(sql, cn)
            Using dr = cm.ExecuteReader
                ListBox1.Items.Clear()
                While dr.Read()
                    ListBox1.Items.Add(dr.GetString(0) & "：" & dr.GetString(1))
                End While
            End Using
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルのレコード数を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)

        Try
            cn.Open()
            Dim sql As String = "select count(*) from 社員"
            Dim cmd As SqlCommand = New SqlCommand(sql, cn)
            Dim num = CInt(cmd.ExecuteScalar())
            cn.Close()
            MessageBox.Show(num & "件のレコードがあります", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try

    End Sub

End Class
```

#####テーブルのフィールド数を取得する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "select * from 社員"
            Dim cmd As SqlCommand = New SqlCommand(sql, cn)
            Using dr = cmd.ExecuteReader()
                MessageBox.Show("フィールド数：" & dr.FieldCount, "通知")
            End Using
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####テーブルのフィールド名取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            cn.Open()
            Dim sql As String = "select * from 社員"
            Dim cmd As SqlCommand = New SqlCommand(sql, cn)
            Using dr = cmd.ExecuteReader()
                ListBox1.Items.Clear()
                For i As Integer = 0 To dr.FieldCount - 1
                    ListBox1.Items.Add($"{i + 1}番目のフィールド：{dr.GetName(i)}")
                Next
            End Using
            cn.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データセットにデータベースのデータを取得
Dataset・・・複数の結果テーブルを扱う
DataTable ・・・一つの結果テーブルを扱う

```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim ds = New DataSet("t_社員")
            ad.Fill(ds, "t_社員")
            MessageBox.Show("データテーブルに取得しました", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim dt = New DataSet
            ad.Fill(dt)
            MessageBox.Show("データテーブルに取得しました", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub
End Class
```

#####データセットのレコードを参照
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim dt = New DataTable()
            ad.Fill(dt)
            Dim q = From r In dt
                    Select String.Join(" ", r.ItemArray)
            ListBox1.DataSource = q.ToList()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データセット内のフィールドの数を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim dt = New DataTable()
            ad.Fill(dt)
            Dim cnt = dt.Columns.Count
            MessageBox.Show($"テーブルのフィールド数：{cnt}", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データセット内のレコードの数を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim dt = New DataTable()
            ad.Fill(dt)
            Dim cnt = dt.Rows.Count
            MessageBox.Show($"テーブルのレコード数：{cnt}", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

End Class
```

#####データセットから条件に合致するデータを取得する
```
Public Class Form1

    '条件を満たすレコードを抽出
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Try
            Dim sql As String = "select * from 社員"
            Dim ad = New SqlDataAdapter(sql, cn)
            Dim dt = New DataTable()
            ad.Fill(dt)
            Dim view = New DataView(dt, "部門コード = 01", "", DataViewRowState.CurrentRows)
            ListBox1.Items.Clear()
            For i As Integer = 0 To view.Count - 1
                Dim s = ""
                For j As Integer = 0 To view.Table.Columns.Count - 1
                    s += view(i)(j) & " "
                Next
                ListBox1.Items.Add(s)
            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message, "通知")
        End Try
    End Sub

    'LINQでレコードを抽出
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim cn As SqlConnection = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable
        ad.Fill(dt)
        Dim q = From t In dt
                Where t("部門コード") = 1
                Select String.Join(" ", t.ItemArray)
        ListBox1.DataSource = q.ToList()
    End Sub

End Class
```

#####データセットのレコードをフィールドの値で並べ替える
```
Public Class Form1

    '条件を満たすレコードを抽出
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim ds = New DataSet("t_社員")
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        ad.Fill(ds, "t_社員")
        Dim view = New DataView(ds.Tables("t_社員"), "", "社員番号 DESC", DataViewRowState.CurrentRows)
        ListBox1.Items.Clear()
        For Each v In view
            ListBox1.Items.Add($"{v("社員番号")}{v("名前")}")
        Next
    End Sub

End Class
```

#####データセットのテーブルのフィールドの型名取得
```
Public Class Form1

    '条件を満たすレコードを抽出
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Dim nam = dt.Columns(0).DataType.ToString()
        MessageBox.Show("フィールドの型名：" + nam, "通知")
    End Sub

End Class
```

#####データセットから指定行のレコード取得
```
Public Class Form1

    '条件を満たすレコードを抽出
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Dim row = dt.Rows(2)
        MessageBox.Show($"{row(0)} {row(1)}", "通知")
    End Sub

End Class
```

#####データセットにテーブルを作成
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ds As New DataSet("生物")
        Dim dt = ds.Tables.Add("恐竜")
        dt.Columns.Add("ID", GetType(Integer))
        dt.Columns.Add("名前", GetType(String))
        MessageBox.Show(
            $"[{ds.Tables(0).TableName}]テーブルを追加しました", "通知")
    End Sub

End Class
```

#####データセットのテーブルにレコード追加
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ds = New DataSet("生物")
        Dim colData = {2, "ブラキオサウルス  "}
        Dim dt = ds.Tables.Add("恐竜")
        dt.Columns.Add("ID", GetType(Integer))
        dt.Columns.Add("名前", GetType(String))
        Dim row = dt.NewRow()
        row("ID") = 1
        row("名前") = "ティラノサウルス"
        dt.Rows.Add(row)
        dt.Rows.Add(colData)
        MessageBox.Show("追加したレコード：　" &
                        ds.Tables(0).Rows(0)(0) &
                        " " &
                        ds.Tables(0).Rows(0)(1), "結果通知")
    End Sub

End Class
```

#####datagridviewにデータ表示
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        DataGridView1.DataSource = dt
    End Sub

End Class
```

#####datagridviewに抽出したレコードを表示
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Dim view = New DataView(dt, "部門コード= 1", "", DataViewRowState.CurrentRows)
        Me.DataGridView1.DataSource = view
    End Sub

End Class
```

#####datagridviewに行ヘッダーを表示しない
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        DataGridView1.RowHeadersVisible = False
        DataGridView1.DataSource = dt
    End Sub

End Class
```

#####datagridviewの指定列を読み取り専用にする
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Me.DataGridView1.DataSource = dt
        Me.DataGridView1.Columns(0).ReadOnly = True
    End Sub

End Class
```

#####datagridviewに行を追加不可にする
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql As String = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Me.DataGridView1.AllowUserToAddRows = False
        Me.DataGridView1.DataSource = dt
    End Sub

End Class
```

#####datagridviewに列を作成してデータ追加
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim row1 = {"001", "ライオン"}
        Dim row2 = {"002", "トラ"}
        Dim row3 = {"003", "ヒョウ"}
        DataGridView1.Columns.Clear()
        DataGridView1.Columns.Add("No", "No.")
        DataGridView1.Columns.Add("Name", "名前")
        DataGridView1.Rows.Add(row1)
        DataGridView1.Rows.Add(row2)
        DataGridView1.Rows.Add(row3)
    End Sub

End Class
```

#####datagridviewの行の編集状態を調べる
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DirectCast(Me.DataGridView1.DataSource, DataTable)

        For i As Integer = 0 To dt.Rows.Count - 1
            System.Diagnostics.Debug.WriteLine(
                i.ToString() + vbTab + dt.Rows(i).RowState.ToString())
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Me.DataGridView1.DataSource = dt
    End Sub

End Class
```

#####datagridviewの編集状態を確定する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dt = DirectCast(DataGridView1.DataSource, DataTable)

        For Each dRow As DataRow In dt.Rows
            If dRow.RowState <> DataRowState.Unchanged Then
                dRow.AcceptChanges()
            End If
        Next

        For i As Integer = 0 To dt.Rows.Count - 1
            System.Diagnostics.Debug.WriteLine(
                i & dt.Rows(i).RowState.ToString())
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        Dim sql = "select * from 社員"
        Dim ad = New SqlDataAdapter(sql, cn)
        Dim dt = New DataTable()
        ad.Fill(dt)
        Me.DataGridView1.DataSource = dt
    End Sub

End Class
```

#####トランザクションを開始、終了する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        cn.Open()
        Dim tr = cn.BeginTransaction()
        MessageBox.Show("トランザクションを開始しました", "通知")
        tr.Commit()
        MessageBox.Show("トランザクションを終了しました", "通知")
        cn.Close()
    End Sub

End Class
```

#####トランザクションを適用する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        cn.Open()
        Dim cmd = cn.CreateCommand()
        Dim tr = cn.BeginTransaction()
        cmd.Connection = cn
        cmd.Transaction = tr
        cmd.CommandText = "insert into 社員 values('10101','まお','3')"
        cmd.ExecuteNonQuery()
        tr.Commit()
        MessageBox.Show("処理を終了しました", "通知")
        cn.Close()
    End Sub

End Class
```

#####トランザクションを中止する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cn = New SqlConnection(
            ConfigurationManager.ConnectionStrings("_02.My.MySettings.SampleDBConnectionString").ConnectionString)
        cn.Open()
        Dim sql As String = "insert into 社員 values('22222','nanana','5')"
        Dim cmd = New SqlCommand(sql, cn)
        Dim tr = cn.BeginTransaction()
        cmd.Transaction = tr
        Try
            cmd.ExecuteNonQuery()
            tr.Commit()
            MessageBox.Show("終了しました", "通知")
        Catch ex As Exception
            tr.Rollback()
            MessageBox.Show(ex.Message, "エラー")
            MessageBox.Show("ロールバックしました", "通知")
        End Try
        cn.Close()
    End Sub

End Class
```

###LINQ

#####LINQの基本
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim lst = New List(Of Control)()
        For Each c As Control In Me.Controls
            lst.Add(c)
        Next

        Dim q = From c In lst
                Where TypeOf c Is Button Select c.Name

        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```

#####LINQで配列を扱う
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim persons = {
            "masuda tomoaki",
            "sato eri",
            "ito yui",
            "masuda daiki",
            "masuda yuriko"}

        Dim q = From p In persons
                Where p.StartsWith("masuda") Select p

        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```

#####LINQでXMLを扱う
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim persons = XElement.Load("C:\Users\ttm11\OneDrive\デスクトップ\persons.xml")

        Dim q = From p In persons.Descendants("person")
                Where p.Element("name").Value.StartsWith("masuda")
                Select p.Element("name").Value

        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```
```
<persons>
<person><name>masuda tomoaki</name><age>49</age></person>
<person><name>masuda yumi</name><age>44</age></person>
<person><name>masuda kaho</name><age>13</age></person>
<person><name>masuda kazuhisa</name><age>7</age></person>
<person><name>shinohara hayato</name><age>18</age></person>
<person><name>shinohara shota</name><age>17</age></person>
</persons>
```

#####LINQでDataSetを扱う
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim ad = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ad.GetData()
        Dim q = From t In table Select t.名前
        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```

#####LINQでデータを並べ替えて取得
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim ad = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ad.GetData()
        Dim q = From t In table Order By t.社員番号 Descending Select t.名前
        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```

#####指定した行番号のレコードを取得する
```
Public Class Form2
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Dim n = Integer.Parse(TextBox1.Text)
        Dim ad = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ad.GetData()
        Dim q = From t In table Order By t.社員番号
                Skip n Take 1
                Select t.社員番号
        ListBox1.DataSource = q.ToList()
    End Sub
End Class
```

#####指定したフィールド名の値を取得する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ent.GetData()
        Dim q = From t In table
                Select New With {t.社員番号, t.名前}

        DataGridView1.DataSource = q.ToList()
    End Sub

End Class
```

#####取得したレコード数を取得する
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ent.GetData()

        Dim q = From t In table
                Select t

        Dim count = q.Count()

        TextBox1.Text = count
    End Sub

End Class
```

#####データの合計値取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ent.GetData()
        Dim q = From t In table
                Select t.部門コード

        Dim sum = q.Sum()

        TextBox1.Text = sum
    End Sub

End Class
```

#####リストボックスにデータバインド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ent.GetData()
        Dim q = From t In table
                Select t.社員番号, t.名前

        ListBox1.DataSource = q.ToList()
    End Sub

End Class
```

#####DataGridViewにデータバインド
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent = New DataSet1TableAdapters.社員TableAdapter()
        Dim table = ent.GetData()
        Dim q = From t In table
                Select t

        DataGridView1.DataSource = q.ToList()
    End Sub

End Class
```

###エラー処理

#####構造化エラー処理
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a As Integer
        Try
            a = Integer.Parse("間違った値")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####すべての例外処理に対処
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a As Integer
        Try
            a = Integer.Parse("間違った値")
        Catch ex As ArgumentNullException
            MessageBox.Show("引数が無効です", "エラー発生")
        Catch ex As Exception
            MessageBox.Show("予期しないエラーが発生しました", "エラー発生")
        End Try
    End Sub

End Class
```

#####例外の後処理
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a As Integer
        Try
            a = 10
            Return
        Catch ex As FormatException
            MessageBox.Show(ex.Message, "エラー発生")
        Finally
            MessageBox.Show("Finallyブロックの処理", "通知")
        End Try
    End Sub

End Class
```

#####例外のメッセージ取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a As Integer
        Try
            a = Integer.Parse("間違った値")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####配列のインデックスが範囲外の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ary = {1, 2, 3}
        Try
            Dim num = ary(5)
        Catch ex As IndexOutOfRangeException
            MessageBox.Show(ex.Message, "エラー")
        End Try
    End Sub

End Class
```

#####無効なメソッドの呼び出しの例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim s = ""
        Try
            System.Diagnostics.Process.Start(s)
        Catch ex As InvalidOperationException
            MessageBox.Show(ex.Message, "エラー")
        End Try
    End Sub

End Class
```

#####例外を呼び出し元で処理
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            SampleProc()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

    Private Sub SampleProc()
        Dim a As Integer
        a = Integer.Parse("間違った値")
        MessageBox.Show($"a = {a}", "通知")
    End Sub

End Class
```

#####例外の種類を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a As Integer
        Try
            a = Integer.Parse("間違った値")
        Catch ex As Exception
            MessageBox.Show(ex.GetType().ToString(), "エラー発生")
        End Try
    End Sub

End Class
```

#####例外が発生した場所を取得
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a = 0
        Try
            a = Integer.Parse("間違った値")
        Catch ex As Exception
            MessageBox.Show(ex.StackTrace, "エラー発生")
        End Try
    End Sub

End Class
```

#####例外を発生させる
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a = 10
        Dim b = 0
        Try
            If b = 0 Then
                Throw New DivideByZeroException("0では除算できません")
            End If
            a = a / b
            MessageBox.Show($"a = {a}", "通知")
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####新しい例外を定義
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim a = 10
        Dim b = 0
        Try
            If b = 0 Then
                Throw New SampleException("0による除算はできません")
            End If
            a = a / b
        Catch ex As Exception
            MessageBox.Show(ex.Message, "エラー")
        End Try
    End Sub

End Class

Public Class SampleException
    Inherits Exception

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(msg As String)
        MyBase.New(msg)
    End Sub

    Public Sub New(msg As String, inner As Exception)
        MyBase.New(msg, inner)
    End Sub
End Class
```

#####引数が無効の場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim s = ""
        Try
            Label1.Text = Integer.Parse(s).ToString()
        Catch ex As FormatException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####引数の値が範囲外の場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim s = "Sample"
        Try
            Label1.Text = s.Substring(7, 2)
        Catch ex As ArgumentOutOfRangeException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####引数がNothingの場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim s1 = "abc"
        Dim s2 = Nothing
        Try
            Label1.Text = s1.Insert(2, s2)
        Catch ex As ArgumentNullException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####IOエラーが発生した場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dname As String = "C:\VB2017\Sample.txt"
        Try
            For Each fname In System.IO.Directory.GetFiles(dname)
                ListBox1.Items.Add(fname)
            Next
        Catch ex As System.IO.IOException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####ファイルが存在しない場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Dim img = Image.FromFile("C:1111.jbg")
        Catch ex As System.IO.FileNotFoundException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

#####フォルダーが存在しない場合の例外
```
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            For Each fname In System.IO.Directory.GetFiles("C:\aaa")
                ListBox1.Items.Add(fname)
            Next
        Catch ex As System.IO.DirectoryNotFoundException
            MessageBox.Show(ex.Message, "エラー発生")
        End Try
    End Sub

End Class
```

###コモンダイアログ

#####ファイルを開くダイアログ
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With OpenFileDialog1
            .Title = "画像ファイルの選択"
            .CheckFileExists = True
            .RestoreDirectory = True
            .Filter = "イメージファイル|*.bmp;*.jpg;*.gif"
        End With

        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Label1.Text = OpenFileDialog1.FileName
            Label2.Text = OpenFileDialog1.SafeFileName
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
        Else
            Label1.Text = ""
            Label2.Text = ""
            PictureBox1.Image = Nothing
        End If
    End Sub
End Class
```

#####名前を付けて保存するダイアログ
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With SaveFileDialog1
            .RestoreDirectory = True
            .OverwritePrompt = True
            .Filter = "JPeg(*.jpg)|*.jpg|Gif(*.gif)|*.gif"
        End With

        If SaveFileDialog1.ShowDialog() = DialogResult.Cancel Then
            Return
        End If

        Label1.Text = Path.GetFileName(SaveFileDialog1.FileName)
        Using fs = DirectCast(SaveFileDialog1.OpenFile(), FileStream)
            If SaveFileDialog1.FilterIndex = 1 Then
                PictureBox1.Image.Save(fs, Imaging.ImageFormat.Jpeg)
            Else
                PictureBox1.Image.Save(fs, Imaging.ImageFormat.Gif)
            End If
        End Using
        Label1.Text = "保存しました"
    End Sub
End Class
```

#####フォントを設定するダイアログボックスを表示する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With FontDialog1
            .ShowColor = True
            .Font = RichTextBox1.SelectionFont
            .Color = RichTextBox1.SelectionColor
        End With

        If FontDialog1.ShowDialog() = DialogResult.OK Then
            With RichTextBox1
                .SelectionFont = FontDialog1.Font
                .SelectionColor = FontDialog1.Color
            End With
        End If
    End Sub
End Class
```

#####色を設定するダイアログ
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ColorDialog1.ShowDialog() = DialogResult.OK Then
            Label1.BackColor = ColorDialog1.Color
        End If
    End Sub
End Class
```

#####フォルダーを選択するダイアログ
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        FolderBrowserDialog1.Description = "フォルダーを選択してください"
        FolderBrowserDialog1.ShowNewFolderButton = False
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            Label1.Text = FolderBrowserDialog1.SelectedPath
        Else
            Label1.Text = ""
        End If
    End Sub
End Class
```

###文字列操作

#####文字コード取得
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim code = Asc("A")
        Label1.Text = code.ToString()
    End Sub
End Class
```

#####文字の長さ取得
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text = TextBox1.Text
        Label1.Text = text.Length.ToString()
    End Sub
End Class
```

#####大文字を小文字にする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text = TextBox1.Text
        Label1.Text = text.ToUpper()
        Label2.Text = text.ToLower()
    End Sub
End Class
```

#####指定位置から指定文字数分の文字を取得
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text As String = TextBox1.Text
        Label1.Text = ""
        If text.Length < 7 Then
            MessageBox.Show("7文字以上入力してください", "通知")
            Return
        End If
        Label1.Text = text.Substring(4, 3)
    End Sub
End Class
```

#####文字列内に指定した文字列が存在するか調べる
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text.Contains("リス") = True Then
            Label1.Text = "含まれています"
        Else
            Label1.Text = "含まれていません"
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If RegexStringValidator.Equals(TextBox1.Text, "ク*マ") Then
            Label1.Text = "含まれています"
        Else
            Label1.Text = "含まれていません"
        End If
    End Sub
End Class
```

#####文字列内から指定した文字列の位置を検索
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text = TextBox1.Text
        Dim pos = -1
        ListBox1.Items.Clear()
        While True
            pos = text.IndexOf("カキ", pos + 1)
            If pos = -1 Then
                Exit While
            End If
            ListBox1.Items.Add((pos + 1) & "文字目")
        End While
    End Sub
End Class
```

#####2つの文字列の大小を比較
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 = TextBox1.Text
        Dim text2 = TextBox2.Text
        Dim ret = text1.CompareTo(text2)

        If ret = 0 Then
            Label1.Text = "同じです"
        ElseIf ret < 0 Then
            Label1.Text = text1 & "の方が小さいです"
        Else
            Label2.Text = text1 & "の方が大きいです"
        End If
    End Sub
End Class
```

#####文字列内の指定文字を別の文字に置き換える
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 = TextBox1.Text
        Label2.Text = text1.Replace("し", "シ")
    End Sub
End Class
```

#####文字列が指定文字列で始まっているか調べる
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 = TextBox1.Text
        If text1.StartsWith("My") Then
            Label1.Text = "Myで始まっています"
        Else
            Label1.Text = "Myで始まっていません"
        End If
    End Sub
End Class
```

#####文字列の前後のスペースを削除する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim t = TextBox1.Text
        If t = String.Empty Then
            Return
        End If
        Label1.Text = "「" + t.Trim() + "」"
        Label2.Text = "「" + t.TrimStart() + "」"
        Label3.Text = "「" + t.TrimEnd() + "」"
    End Sub
End Class
```

#####文字列内から指定位置の文字を削除
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 = TextBox1.Text
        Dim text2 = TextBox2.Text
        If text1.Length < 4 Then
            MessageBox.Show("4文字以上入力してください", "通知")
            Return
        End If
        Label1.Text = text1.Remove(1, 3)
    End Sub
End Class
```

#####文字列内に別の文字列を挿入する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 = TextBox1.Text
        Dim text2 = TextBox2.Text
        If text1.Length < 2 Then
            Return
        End If
        Label1.Text = text1.Insert(2, text2)
    End Sub
End Class
```

#####文字列が指定した文字数になるまでスペースを入れる
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim Text1 = TextBox1.Text
        Label1.Text = "「" + Text1.PadLeft(15) + "」"
        Label2.Text = "「" + Text1.PadRight(15) + "」"
    End Sub
End Class
```

#####文字列を指定した区切り文字で分割する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim text1 As String = TextBox1.Text
        Dim textArray = text1.Split("/"c)
        ListBox1.Items.Clear()
        For Each text2 As String In textArray
            ListBox1.Items.Add(text2)
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim text1 As String = TextBox1.Text
        Dim textArray = text1.Split({"/"}, StringSplitOptions.None)
        ListBox1.Items.Clear()
        For Each text2 As String In textArray
            ListBox1.Items.Add(text2)
        Next
    End Sub
End Class
```

#####文字列配列の各要素を連結する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim textArray = {"aaa", "bbb", "ccc"}
        Dim mark = TextBox1.Text
        Label1.Text = String.Join(mark, textArray)
    End Sub
End Class
```

#####数値と日付の書式を指定する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim num = 10.12345
        Dim myData = DateTime.Now
        Label1.Text = myData.ToString("yy/MM/dd(ddd) HH:mm:ss")
        Label2.Text = myData.ToString("tt h:m:s")
        Label3.Text = myData.ToString("D")
        Label4.Text = num.ToString("000.000")
        Label5.Text = num.ToString("0.00%")
        Label6.Text = num.ToString("#.#")
        Label7.Text = num.ToString("C")
        Label8.Text = num.ToString("P")
    End Sub
End Class
```

###ユーザーインターフェース

#####フォームのサイズを固定
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.FormBorderStyle = FormBorderStyle.FixedToolWindow
        Label1.Text = "fixedtoolwindow"
    End Sub
End Class
```

#####最大化・最小化ボタンを非表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Me.MaximizeBox = True And Me.MinimizeBox = True Then
            Me.MaximizeBox = False
            Me.MinimizeBox = False
        Else
            Me.MaximizeBox = True
            Me.MinimizeBox = True
        End If
    End Sub
End Class
```

#####ヘルプボタン表示
[プロパティウィンドウで操作]
１、最大化・最小化ボタンを非表示にする
２、ヘルプボタンを表示する
３、イベントの「HelpRequested」をダブルクリック

```
Public Class Form1
    Private Sub Form1_HelpRequested(sender As Object, hlpevent As HelpEventArgs) Handles MyBase.HelpRequested
        MessageBox.Show("ボタンをクリックすると終了します。")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class
```

#####フォームをモニターの大きさに合わせる
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.WindowState = FormWindowState.Normal
    End Sub
End Class
```

#####フォームを表示する/閉じる
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newForm As New Form3
        newForm.Label1.Text = "モーダルで表示しています"
        newForm.ShowDialog()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim newForm As New Form3
        newForm.Label1.Text = "モードレスで表示しています"
        newForm.Show()
    End Sub
End Class
```
```
Public Class Form3
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class
```

#####フォームの表示位置を指定
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newForm As New Form3
        newForm.StartPosition = FormStartPosition.Manual
        newForm.Location = New Point(0, 0)
        newForm.Show()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim newForm As New Form3
        newForm.StartPosition = FormStartPosition.CenterScreen
        newForm.Show()
    End Sub
End Class
```

#####フォームの大きさを変更
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Width += 10
        Me.Height += 10
    End Sub
End Class
```

#####デフォルトボタン、キャンセルボタン設定
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MessageBox.Show("[OK]ボタンがクリックされました", "結果")
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        MessageBox.Show("[キャンセル]します", "結果")
        Me.Close()
    End Sub
End Class
```

#####フォームやコントロールの初期設定
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.AcceptButton = Button1
        Me.CancelButton = Button2
        Label1.Text = "初期設定"
        Button1.Text = "OK"
        Button2.Text = "Cancel"
    End Sub
End Class
```

#####フォームを半透明にする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Opacity -= 0.1
    End Sub
End Class
```

#####ほかのフォームのコントロールの値を参照
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim newForm As New Form3
        newForm.ShowDialog()
        Label1.Text = newForm.TextBox1.Text
    End Sub
End Class
```

#####ダイアログボックスでクリックされた結果をフォームで取得
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = ""
        Dialog1.ShowDialog()
        Select Case Dialog1.DialogResult
            Case DialogResult.OK
                Label1.Text = "OK"
            Case DialogResult.Cancel
                Label1.Text = "Cancel"
        End Select
    End Sub
End Class
```

#####任意に位置に文字列を表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.AutoSize = False
        Label1.Size = New Size(300, 40)
        Label1.Text = "現在の日時：" + DateTime.Now.ToString()
        Label1.ForeColor = Color.DarkBlue
        Label1.BorderStyle = BorderStyle.FixedSingle
        Label1.TextAlign = ContentAlignment.MiddleCenter
    End Sub
End Class
```

#####リンクラベルでWEBページにリンクする
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        LinkLabel1.Text = "サイトを開きます"
        LinkLabel1.Links.Add(0, 3, "www.shuwasystem.co.jp")
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Dim linkTarget As String
        linkTarget = LinkLabel1.Links(0).LinkData.ToString()
        System.Diagnostics.Process.Start(linkTarget)

        LinkLabel1.LinkVisited = True
    End Sub
End Class
```

#####リンクラベルで別のフォームにリンクする
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        LinkLabel1.Text = "別のフォームを開きます"
        LinkLabel1.LinkArea = New LinkArea(2, 4)
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Form3.ShowDialog()
        LinkLabel1.LinkVisited = True
    End Sub
End Class
```

#####ボタンを使う
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MessageBox.Show("ボタンがクリックされました", "結果")
    End Sub
End Class
```

#####テキストボックスで文字の入力を取得する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MessageBox.Show("入力内容" + TextBox1.Text, "結果")
    End Sub
End Class
```

#####入力する文字の種類を指定する
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1.ImeMode = ImeMode.Off
        TextBox2.ImeMode = ImeMode.On
    End Sub
End Class
```

#####テキストボックスを読み取り専用にする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.ReadOnly = True
        TextBox2.Enabled = False
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TextBox1.ReadOnly = False
        TextBox2.Enabled = True
    End Sub
End Class
```

#####入力できる文字数を制限
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text.Length < 4 Then
            Label1.Text = TextBox1.Text.Length.ToString & "・・・文字数が足りません"
        Else
            Label1.Text = TextBox1.Text.Length.ToString
        End If
    End Sub
End Class
```

#####テキストボックスに指定した形式でデータを入力
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If MaskedTextBox1.MaskCompleted Then
            If IsDate(MaskedTextBox1.Text) Then
                Label1.Text = MaskedTextBox1.Text
            Else
                Label1.Text = "正確に入力してください"
                MaskedTextBox1.Clear()
            End If
        Else
            Label1.Text = "最後まで入力してください"
        End If
    End Sub
End Class
```

#####複数選択できる選択肢を設ける
```
Public Class Form1
    Dim a1 As Integer = 1000
    Dim a2 As Integer = 500
    Dim a3 As Integer = 10
    Dim a4 As Integer = 5

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim sum As Integer = 0

        If CheckBox1.Checked Then
            sum += a1
        End If
        If CheckBox2.Checked Then
            sum += a2
        End If
        If CheckBox3.Checked Then
            sum += a3
        End If
        If CheckBox4.Checked Then
            sum += a4
        End If

        Label1.Text = sum.ToString("#,###円")
    End Sub
End Class
```

#####１つだけ選択できる選択肢を設ける
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myString As String
        If RadioButton1.Checked Then
            myString = RadioButton1.Text
        ElseIf RadioButton2.Checked Then
            myString = RadioButton2.Text
        End If
        Label1.Text = myString
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RadioButton1.Checked = True
    End Sub
End Class
```

#####ラジオボタンのリストをスクロールする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myRB As RadioButton
        For Each myRB In Panel1.Controls
            If myRB.Checked Then
                Label1.Text = myRB.Text
                Exit For
            End If
        Next
    End Sub
End Class
```

#####グループごとに1つだけ選択できるようにする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myRB As RadioButton
        Dim myText As String

        For Each myRB In GroupBox2.Controls
            If myRB.Checked Then
                myText = myRB.Text
                Exit For
            End If
        Next

        Label1.Text = myText
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RadioButton1.Checked = True
    End Sub
End Class
```

#####ピクチャーボックスに画像を表示・非表示にする
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If CheckBox1.Checked Then
            PictureBox1.Image = Image.FromFile("C:\Users\aaa.jpg")
            PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
        Else
            PictureBox1.Image.Dispose()
            PictureBox1.Image = Nothing
        End If
    End Sub
End Class
```

#####ピクチャーボックスに画像を重ねて表示する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If CheckBox1.Checked Then
            PictureBox1.Image = Image.FromFile("C:\Users\aaa.jpg")
            PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
        Else
            PictureBox1.Image.Dispose()
            PictureBox1.Image = Nothing
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        PictureBox1.BackgroundImage = Image.FromFile("C:\Users\bbb.jpg")
        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
    End Sub
End Class
```

#####リストボックスに項目を追加、削除する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myArray() As String = {"ホワイト", "イエロー", "ブルー"}
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(myArray)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If ListBox1.Items.Count <> 0 Then
            ListBox1.Items.RemoveAt(0)
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If ListBox1.Items.Count <> 0 Then
            ListBox1.Items.RemoveAt(ListBox1.Items.Count - 1)
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.Items.Add("ホワイト")
        ListBox1.Items.Add("イエロー")
        ListBox1.Items.Add("ブルー")
    End Sub

End Class
```

#####リストボックスに順番を指定して項目を追加
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text <> "" Then
            ListBox1.Items.Insert(0, TextBox1.Text)
            TextBox1.Text = ""
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If TextBox1.Text <> "" Then
            ListBox1.Items.Insert(ListBox1.Items.Count, TextBox1.Text)
            TextBox1.Text = ""
        End If
    End Sub

End Class
```

#####リストボックスで項目を選択し、その項目を取得する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ListBox1.SelectedIndex = -1 Then
            Label1.Text = "選択されていません"
        Else
            Label1.Text = ListBox1.SelectedIndex + 1 & "番目: " & ListBox1.SelectedItem
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ListBox1.ClearSelected()
        Label1.Text = ""
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.SelectedIndex = 0
    End Sub
End Class
```

#####リストボックスで複数選択された項目を取得
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myList As Object
        For Each myList In ListBox1.SelectedItems
            ListBox2.Items.Add(myList)
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim i As Integer
        For i = ListBox1.Items.Count - 1 To 0 Step -1
            If ListBox1.GetSelected(i) Then
                ListBox1.Items.RemoveAt(i)
            End If
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim myArray() As String = {"A4用紙", "ペン", "消しゴム", "ファイル", "ノート", "のり"}
        ListBox1.Items.AddRange(myArray)
        ListBox1.SelectionMode = SelectionMode.MultiSimple
        ListBox2.SelectionMode = SelectionMode.MultiSimple
    End Sub
End Class
```

#####チェックボックス付きリストボックス
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myItem As Object
        ListBox1.Items.Clear()
        For Each myItem In CheckedListBox1.CheckedItems
            ListBox1.Items.Add(myItem)
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim myArray() As String = {"アジア", "オセアニア", "アメリカ", "ヨーロッパ", "アフリカ"}
        CheckedListBox1.Items.AddRange(myArray)
        CheckedListBox1.SetItemChecked(0, True)
    End Sub
End Class
```

#####コンボボックス
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ComboBox2.SelectedIndex = -1 Then
            Label1.Text = "選択されていません"
        Else
            Label1.Text = ComboBox2.Text
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ComboBox2.Items.Add("イチゴパフェ")
        ComboBox2.Items.Add("バナナアイス")
        ComboBox2.Items.Add("フォンダンショコラ")
        ComboBox2.Items.Add("パンケーキ")
    End Sub
End Class
```

#####タブコントロール
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myTP As TabPage
        Dim myRB As RadioButton
        ListBox1.Items.Clear()
        For Each myTP In TabControl1.TabPages
            For Each myRB In myTP.Controls
                If myRB.Checked Then
                    ListBox1.Items.Add(myRB.Text)
                End If
            Next
        Next
    End Sub
End Class
```

#####カレンダーで日付選択
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = DateTimePicker1.Value.ToShortDateString
        TextBox2.Text = DateTimePicker1.Value
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DateTimePicker1.Format = DateTimePickerFormat.Long
        DateTimePicker1.Value = DateTime.Now
        DateTimePicker1.MinDate = #1/1/1960#
        DateTimePicker1.MaxDate = #12/31/2020#
    End Sub
End Class
```

#####日付範囲を選択できるカレンダー
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim startDay As DateTime = MonthCalendar1.SelectionStart
        Dim endDay As DateTime = MonthCalendar1.SelectionEnd
        Label1.Text = startDay.ToLongTimeString
        Label2.Text = endDay.ToLongTimeString
        Label3.Text = endDay.Subtract(startDay).Days - 1
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MonthCalendar1.MaxSelectionCount = 15
    End Sub
End Class
```

#####タイマー
```
Public Class Form1
    Dim startTime As New TimeSpan(0, 0, 0)
    Dim addSecond As New TimeSpan(0, 0, 1)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer1.Enabled = Not Timer1.Enabled
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Timer1.Enabled = False
        startTime = New TimeSpan(0, 0, 0)
        Label1.Text = startTime.ToString
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        startTime = startTime + addSecond
        Label1.Text = startTime.ToString()
        If startTime = New TimeSpan(3, 0, 0) Then
            Timer1.Stop()
        End If
    End Sub
End Class
```

#####メニューバーを作成
```
Public Class Form1

    Private Sub 左揃えToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 左揃えToolStripMenuItem.Click
        TextBox1.TextAlign = HorizontalAlignment.Left
    End Sub

    Private Sub 右揃えToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 右揃えToolStripMenuItem.Click
        TextBox1.TextAlign = HorizontalAlignment.Right
    End Sub

    Private Sub 中央揃えToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 中央揃えToolStripMenuItem.Click
        TextBox1.TextAlign = HorizontalAlignment.Center
    End Sub
End Class
```

#####メニューコマンドを無効にする
```
Public Class Form1
    Private Sub 中央揃えToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 中央揃えToolStripMenuItem.Click
        TextBox1.TextAlign = HorizontalAlignment.Center
        左揃えToolStripMenuItem.Enabled = True
        右揃えToolStripMenuItem.Enabled = True
        中央揃えToolStripMenuItem.Enabled = False
    End Sub
End Class
```
#####メニューコマンドにチェックマークを付ける
```
Public Class Form1
    Dim futoji As FontStyle
    Dim syatai As FontStyle

    Private Sub 太字ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 太字ToolStripMenuItem.Click
        If 太字ToolStripMenuItem.Checked Then
            futoji = FontStyle.Regular
            太字ToolStripMenuItem.Checked = False
        Else
            futoji = FontStyle.Bold
            太字ToolStripMenuItem.Checked = True
        End If
        TextBox1.Font = New Font(TextBox1.Font, futoji + syatai)
    End Sub

    Private Sub 斜体ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 斜体ToolStripMenuItem.Click
        If 斜体ToolStripMenuItem.Checked Then
            syatai = FontStyle.Regular
            斜体ToolStripMenuItem.Checked = False
        Else
            syatai = FontStyle.Italic
            斜体ToolStripMenuItem.Checked = True
        End If
        TextBox1.Font = New Font(TextBox1.Font, futoji + syatai)
    End Sub
End Class
```

#####ショートカットキーを割り当てる
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        太字ToolStripMenuItem.ShortcutKeys = Keys.Control Or Keys.B
    End Sub
End Class
```

#####ショートカットメニューをつける
```
Public Class Form1
    Private Sub 中央揃えToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 中央揃えToolStripMenuItem.Click
        Dim obj As TextBox = ContextMenuStrip1.SourceControl
        obj.TextAlign = HorizontalAlignment.Center
    End Sub
End Class
```

#####ツールバー作成
```
Public Class Form1
    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        Dim obj As Object
        For Each obj In Me.Controls
            If TypeOf obj Is TextBox AndAlso TryCast(obj, TextBox).Focused Then
                Dim objText = TryCast(obj, TextBox)
                objText.Font = New Font(objText.Font, FontStyle.Bold)
            End If
        Next
    End Sub
End Class
```

#####ステータスバーを作成する
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ToolStripStatusLabel1.Text = Today.ToShortDateString
    End Sub
End Class
```

#####プログレスバー
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = 100000
        ProgressBar1.Value = 0
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim i As Long
        For i = 0 To 1000000
            ProgressBar1.Value = 1
        Next
        Label1.Text = "処理は終了しました"
    End Sub
End Class
```

#####階層構造表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = TreeView1.SelectedNode.FullPath
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim myNode As TreeNode = TreeView1.SelectedNode
        If TextBox1.Text = "" Then Exit Sub
        If myNode Is Nothing Then
            MessageBox.Show("項目を選択してください", "通知")
            Exit Sub
        End If
        myNode.Nodes.Add(New TreeNode(TextBox1.Text))
    End Sub
End Class
```

#####リストビューにファイル一覧を表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dirInfo As System.IO.DirectoryInfo
        Dim fileList() As System.IO.FileInfo
        Dim fileInfo As System.IO.FileInfo

        ListView1.Items.Clear()

        If System.IO.Directory.Exists(TextBox1.Text) = False Then
            MessageBox.Show("フォルダーが存在しません", "通知")
            Exit Sub
        End If

        dirInfo = New System.IO.DirectoryInfo(TextBox1.Text)
        fileList = dirInfo.GetFiles
        For Each fileInfo In fileList
            Dim fileItem As ListViewItem = New ListViewItem(fileInfo.Name)
            fileItem.SubItems.Add(fileInfo.Length.ToString)
            fileItem.SubItems.Add(fileInfo.LastWriteTime)
            ListView1.Items.Add(fileItem)
        Next
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListView1.Clear()
        ListView1.View = View.Details
        ListView1.Columns.Add("ファイル名", 100)
        ListView1.Columns.Add("ファイルサイズ", 60, HorizontalAlignment.Right)
        ListView1.Columns.Add("更新日", 120)
    End Sub
End Class
```

#####リストビューに画像一覧を表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim i As Integer
        Dim myPath As String = "C:\Users\ttm11\OneDrive\画像\カメラ ロール"

        Dim imgFile() As String = System.IO.Directory.GetFiles(myPath, "*.jpg")

        For i = 0 To imgFile.Length - 1
            Dim myImg As Image = Image.FromFile(imgFile(i))
            ImageList1.Images.Add(myImg)
            ListView1.Items.Add(imgFile(i), i)
            myImg.Dispose()
        Next

    End Sub
End Class
```

#####リッチテキストボックスの編集を元に戻す
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim ans As Integer
        Label1.Text = RichTextBox2.UndoActionName
        ans = MessageBox.Show("処理を戻しますか", "確認", MessageBoxButtons.YesNo)
        If ans = DialogResult.Yes Then
            RichTextBox2.Undo()
        End If
        Label1.Text = ""

    End Sub
End Class
```

#####リッチテキストボックスのフォントと色を設定する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        RichTextBox2.SelectionFont = New Font("MS ゴシック", FontStyle.Italic)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If RichTextBox2.SelectionColor <> Color.Red Then
            RichTextBox2.SelectionColor = Color.Red
        Else
            RichTextBox2.SelectionColor = Color.Black
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim myFont As Font = RichTextBox2.SelectionFont
        Dim myFS As FontStyle

        If RichTextBox2.SelectionFont.Bold = False Then
            myFS = FontStyle.Bold
        Else
            myFS = FontStyle.Regular
        End If
        RichTextBox2.SelectionFont = New Font(myFont.FontFamily, myFont.Size, myFS)
    End Sub
End Class
```

#####リッチテキストボックスの文字を検出
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pos As Integer
        RichTextBox2.SelectionStart = RichTextBox1.SelectionStart +
            RichTextBox2.SelectionLength
        RichTextBox2.SelectionLength = 0
        RichTextBox2.Focus()
        pos = RichTextBox2.Find(TextBox1.Text, RichTextBox2.SelectionStart, RichTextBoxFinds.None)
    End Sub
End Class
```

#####リッチテキストボックスにファイルの内容を表示
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If System.IO.File.Exists(TextBox1.Text) = False Then
            MessageBox.Show("ファイルが存在してません", "通知")
            Exit Sub
        End If
        If TextBox1.Text.EndsWith("txt") Then
            RichTextBox2.LoadFile(TextBox1.Text, RichTextBoxStreamType.PlainText)
        ElseIf TextBox1.Text.EndsWith("rtf") Then
            RichTextBox2.LoadFile(TextBox1.Text, RichTextBoxStreamType.RichText)
        Else
            MessageBox.Show("形式が違います", "通知")
        End If
    End Sub
End Class
```

#####リッチテキストボックスの内容をファイルに保存する
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If System.IO.Directory.Exists(TextBox1.Text) = False Then
            MessageBox.Show("フォルダーが存在しません", "通知")
            Exit Sub
        End If

        If TextBox1.Text = "" Then
            MessageBox.Show("ファイル名を選択してください", "通知")
        End If
        RichTextBox2.SaveFile(TextBox1.Text & "\" & TextBox2.Text & ".rtf", RichTextBoxStreamType.RichText)
        MessageBox.Show("ファイルを保存しました", "結果")
    End Sub
End Class
```

#####スピンボタンで数値を入力
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        NumericUpDown1.Minimum = 1
        NumericUpDown1.Maximum = 100
        NumericUpDown1.Value = 50
        NumericUpDown1.Increment = 5
    End Sub
End Class
```

#####ドラッグで数値変更
```
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TrackBar1.Minimum = 10
        TrackBar1.Maximum = 30
        TrackBar1.Value = 10
        TrackBar1.TickFrequency = 1
        TrackBar1.SmallChange = 1
        TrackBar1.LargeChange = 5
    End Sub

    Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
        TextBox1.Text = TrackBar1.Value.ToString()
        Dim myFont As Font = Label1.Font
        Label1.Font = New Font(myFont.FontFamily, TrackBar1.Value)
    End Sub
End Class
```

#####パネル上のコントロールを順に参照
```
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim panelItem As Object
        For Each panelItem In Panel1.Controls
            panelItem.text = panelItem.GetType.Name
        Next
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim panelItem As Object
        For Each panelItem In Panel1.Controls
            panelItem.text = ""
        Next
    End Sub
End Class
```