VB.net 初級プログラム 1回 テキストファイル読み込み プログラム開発
環境
Windows10Pro
VisualStudio2017 VB.net(VisualBasic)
VB.net
・コードフロー、流れ
テキストファイル読み込み カンマ区切り
1行ずつListBoxに追加
ListBoxを選択すると1行のテキストが表示される カンマ区切りを分割
(動画はこれから)
(コード)
Imports System.IO Imports System.IO.File Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim defalutPath As String defalutPath = "c:\vb.net\vb.csv" TextBox1.Text = defalutPath End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim path As String path = TextBox1.Text If System.IO.File.Exists(path) = False Then 'ファイルが存在しない場合の処理。ファイルがないと読み込みができないので処理しない MessageBox.Show("ありません。もう一度確認して") Return End If 'usingは、TryCatchの代わりで便利 Using st = New System.IO.StreamReader(path) Dim line = st.ReadLine() While line IsNot Nothing ListBox1.Items.Add(line) line = st.ReadLine() End While End Using End Sub Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged Dim text1 As String text1 = ListBox1.SelectedItem ' CSVのカンマ区切りでテキストを配列に入れる Dim textArray = text1.Split(","c) If textArray.Length >= 3 Then txtBoxSeg1.Text = textArray(0) txtBoxSeg2.Text = textArray(1) txtBoxSeg3.Text = textArray(2) Else txtBoxSeg1.Text = textArray(0) End If End Sub End Class
参考図書
現場ですぐに使える! Visual Basic 2017逆引き大全 555の極意