Answer on Question# 38917 – Saving combobox settings - Programming, Visual Basic
To keep combobox states, the application need to store its settings in outer storage: plain text file, XML, CSV or other file formats, database or windows registry.
Below is the example for most simple case with plain text file. The form has two comboboxes and "Save" and "Load" buttons. The applications writes and reads the selected index for each combobox in the file.
Imports System.IO
Public Class Form1
'populating comboboxes with test values
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("test1")
ComboBox1.Items.Add("test2")
ComboBox1.Items.Add("test3")
ComboBox2.Items.Add("test1")
ComboBox2.Items.Add("test2")
ComboBox2.Items.Add("test3")
End Sub
'Load settings button
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Loading settings file into streamreader
Dim reader As New StreamReader(Application.StartupPath & "\settings.txt")
Dim line As String = ""
'reading file line by line
Dim settings() As String
While reader.Peek() > -1
line = reader.ReadLine
'splitting each line into 2-dimensional array, using "=" as separator
settings = line.Split("="c)
'selecting corresponding comboboxes
Select Case settings(0)
Case "Box1"
ComboBox1.SelectedIndex = CInt(settings(1))
Case "Box2"
ComboBox2.SelectedIndex = CInt(settings(1))
End Select
End While
reader.Close()
End Sub
'Save settings button
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'opening streamwriter object, to write into the settings file
Dim writer As New StreamWriter(Application.StartupPath & "\settings.txt")
'writing selected indexes into the settings file
writer.WriteLine("Box1=" & ComboBox1.SelectedIndex.ToString())
writer.WriteLine("Box2=" & ComboBox2.SelectedIndex.ToString())
writer.Close()
End Sub
End ClassThe approach is similar for storing combobox text values. Save routine should write lines with corresponding box values:
For i = 0 To ComboBox1.Items.Count - 1
writer.WriteLine("box1Value=" & ComboBox1.Items.Item(i).ToString())
NextThe reading routine should populate comboboxes with values retrieved with settings file:
While reader.Peek() > -1
line = reader.ReadLine
'splitting each line into 2-dimensional array, using "=" as separator
settings = line.Split("="c)
'selecting corresponding comboboxes
Select Case settings(0)
Case "box1Value"
ComboBox1.Items.Add(settings(1))
End Select
End While
Comments
Dear Ghulam Murtaza. You're welcome. We are glad to be helpful. If you really liked our service please press like-button beside answer field. Thank you!
Thank you sir. I will be in touch with you for more help.