renu
renu

Reputation:

combobox in vb.net

how to hide or disable items in one combobox on the basis of selected item in another combobox in vb.net?

Upvotes: 0

Views: 4573

Answers (3)

pharophy
pharophy

Reputation: 781

I was just trying to fix an issue with this. It turned out when I cleared the items in the ComboBox and set the selected index to -1 it threw an Exception that it cannot find the selected index. My solution was the following:

using System.Web.UI.WebControls;

namespace AjaxControlToolkit.Extensions
{
    public static class ComboBoxExtension
    {
        public static void ForceClearSelectedIndex(this AjaxControlToolkit.ComboBox comboBox)
        {
            if (comboBox.Items.Count > 0)
                comboBox.Items.Clear();
            comboBox.Items.Add(new ListItem(string.Empty, string.Empty));
            comboBox.Text = string.Empty;
        }
    }
}

Then in the first combobox's ItemInserted Event, or selected index / text changed event you can simply call:

ComboBoxName.ForceClearSelectedIndex();

Putting it all together you can do this:

protected void tbxCustomerName_TextChanged(object sender, EventArgs e)
    {
        if (Customers.Count > 0)
        {
            var datasource = Devices.Where(d => d.Customer.FullName == tbxCustomerName.SelectedItem.Text);
            tbxDeviceName.DataSource = datasource;
            tbxDeviceName.DataTextField = "Name";
            tbxDeviceName.DataValueField = "Device_ID";
            tbxDeviceName.DataBind();
        }
        else
        {
            tbxDeviceName.ForceClearSelectedIndex();
        }
    }

Not in VB, but you can easily convert it.

Upvotes: 0

Drahcir
Drahcir

Reputation: 12621

As gerrie said , you have to make a condition in the second combobox selected indexed changed event, like so :

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedValue = "my Value" Then
        ComboBox2.Visible = False
    End If
End Sub

Where "my value" is a value I have in combobox1

Edit :

The combobox keeps the values inserted unless you clear them. By using this line of code

ComboBox2.Items.Clear() 

Or otherwise you put the values in a list like a Datatable and point the combobox datasource of that specific Datatable

Upvotes: 2

Gerrie Schenck
Gerrie Schenck

Reputation: 22378

Manipulate the datasource of the second combobox in the selected index changed event of the first one.

Upvotes: 2

Related Questions