Set ComboBox Default value on change using C# and VB.Net in Windows Form

Last Reply 7 months ago By dharmendr

Posted 7 months ago

I need a combobox filled with cash as default value using case statement in c#

I HAVE A COMBOBOX WITH VALUES SUCH AS A,B,CASH,X ETC.

I NEED IT TO DISPLAY CASH AS DEFAULT ALWAYS.

SELECTED INDEX OF CASH IS 24

it works fine on load time.

on clicking combobox it changes its value. i need it not to change.

Posted 7 months ago

Hi gokuldas,

Check this example. Now please take its reference and correct your code.

C#

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
                    new DataColumn("Text", typeof(string)),
                    new DataColumn("Value", typeof(string)) });
    dt.Rows.Add("A", "A");
    dt.Rows.Add("B", "B");
    dt.Rows.Add("CASH", "CASH");
    dt.Rows.Add("X", "X");
    comboBox1.DataSource = dt;
    comboBox1.DisplayMember = "Text";
    comboBox1.ValueMember = "Value";
    // Set the Default Value.
    comboBox1.SelectedValue = "CASH";
}

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    // Do the task with ComboBox selected Value.
    MessageBox.Show("Selected Type : " + comboBox1.SelectedValue.ToString());
    // Set the Default Value again.
    comboBox1.SelectedValue = "CASH";
}

VB.Net

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Text", GetType(String)), New DataColumn("Value", GetType(String))})
    dt.Rows.Add("A", "A")
    dt.Rows.Add("B", "B")
    dt.Rows.Add("CASH", "CASH")
    dt.Rows.Add("X", "X")
    comboBox1.DataSource = dt
    comboBox1.DisplayMember = "Text"
    comboBox1.ValueMember = "Value"
    ' Set the Default Value.
    comboBox1.SelectedValue = "CASH"
End Sub

Private Sub comboBox1_SelectionChangeCommitted(sender As System.Object, e As System.EventArgs) Handles comboBox1.SelectionChangeCommitted
    ' Do the task with ComboBox selected Value.
    MessageBox.Show("Selected Type : " & comboBox1.SelectedValue.ToString())
    ' Set the Default Value again.
    comboBox1.SelectedValue = "CASH"
End Sub

Screenshot