locked
ComboBox Binding with a Blank Selected Index Initially??? RRS feed

  • Question

  • I'm making a search engine windows app that contains ComboBoxes that are bound to my SQL Server database.  It would be so much better that once my ComboBox is bound that I could have no item selected (so a blank) incase they don't want to include that in their search but I can't seem to do that without putting in a blank record in my database and that seem soooooo wrong. 

    The only answer I can think of is maybe populate an RA with the data leaving index[0] a blank and then binding to the RA.  But I don't even know if I can bind to an RA.  If anyone thinks this is a good idea I'd love a code example.

    If anyone has any ideas, workarounds or just a simple answer that I've missed, it would be greatly appreciated.  I know the solution is out there but I'm too new to this to know what it might be.

    Thanks in advance.

    Martin

    Sunday, May 21, 2006 8:34 PM

Answers

  • Hi there,

    I'm joining you a little late but as I see it, your problem is that the combo box initially has a selected value, which is the first value in the list but you don't want an item selected initially.

    As the errors you are getting show, you can't mess with the items in a bound combo box. However, if you put the following code right before the end of your function:

    ((ComboBox) cbtrl).SelectedIndex = -1

    I believe that this will set it so that no value is initially selected. Later, when you have to build your search query, you can test for the selected index in the combo box and if it's < 0 then you know nothing's selected and you can exclude a condition from your search.

    Also, where are you calling FillComboBoxControl() from? If you are calling it from your form's Load() handler then it's also feasible to set the SelectedIndex property to -1 in the last statement before the end of the Load() handler.

    Hope that helps a bit, but sorry if it doesn't
    Wednesday, May 24, 2006 7:25 AM

All replies

  • Typically after the ComboBox is bound you can add something as simple as:

    comboBox1.Items.Insert(0, new ListItem("Select",string.Empty));

    which will be selected intially.

    Regards,

    Dave

    Sunday, May 21, 2006 10:54 PM
  • I just tried to put in your code and it doesn't like new ListItem("Select", string.empty) asks if I'm missing "the type or namespace name 'ListItem' could not be found (are you missing a using directive or an assembly reference?)"

    I would have thought I was using it... and I put my function at the bottom just incase I'm an idiot :)

    That aside I played with it abit and it told "Items collection cannot be modified when the DataSource property is set."  Can I just set the DataSource to null then insert if I find out which object I need to use to insert an item?

     

    #region Using Directives

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data; // Using ADO.NET namespace

    using System.Data.SqlClient; // Use SQL Server data provider namespace

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    #endregion

    // My Function

    private void FillComboBoxControl(string dbconn, Control cbctrl)

    {

    string dbsql = BuildComboBoxSQL(cbctrl),

    dbtbl = FindControlDataTable(cbctrl),

    dbcol = FindControlDataColumn(cbctrl),

    dbcolID = dbcol + "ID";

    // Specify SQL Server-specific connection string

    SqlConnection thisConnection = new SqlConnection(dbconn);

    // Create DataAdapter object

    SqlDataAdapter thisAdapter = new SqlDataAdapter(dbsql, thisConnection);

    // Create DataSet to contain related data tables, rows, and columns

    DataSet thisDataSet = new DataSet();

    // Fill DataSet using query defined previously for DataAdapter

    thisAdapter.Fill(thisDataSet, dbtbl);

    // Bind ComboBox control to dataset

    ((ComboBox)cbctrl).DataSource = thisDataSet.Tables[dbtbl];

    ((ComboBox)cbctrl).ValueMember = dbcolID;

    ((ComboBox)cbctrl).DisplayMember = dbcol;

    // WORKS TO THIS POINT THEN DOESN'T LIKE ListItem

    ((ComboBox)cbctrl).Items.Insert(0, new ListItem("Select", string.Empty));

    // Close connection

    thisConnection.Close();

    }

    Sunday, May 21, 2006 11:08 PM
  • My Apologies. That is the code for a DropDownList in ASP.NET.

    For Winforms, the statement is:

    comboBox1.Items.Insert(int index, object item);

    so you could write:

    comboBox1.Items.Insert(0,string.Empty);

    Regards,

    Dave

    Monday, May 22, 2006 1:59 AM
  • If I use this code below:

    ((ComboBox)cbctrl).Items.Insert(0, string.Empty);

    It gives me this as an error:

    Argument Exception Not Handled

    "Items collection cannot be modified when the DataSource property is set."

    Is there another way to bind this combobox and be able to insert a blank index[0] so I don't get this error thrown?  I tried setting the DataSource to null but that seems to clear the combobox?

    private void FillComboBoxControl(string dbconn, Control cbctrl)

    {

        string dbsql = BuildComboBoxSQL(cbctrl),

        dbtbl = FindControlDataTable(cbctrl),

        dbcol = FindControlDataColumn(cbctrl),

        dbcolID = dbcol + "ID";

        SqlConnection thisConnection = new SqlConnection(dbconn);

        SqlDataAdapter thisAdapter = new SqlDataAdapter(dbsql, thisConnection);

        DataSet thisDataSet = new DataSet();

        thisAdapter.Fill(thisDataSet, dbtbl);

     

        ((ComboBox)cbctrl).DataSource = thisDataSet.Tables[dbtbl];

        ((ComboBox)cbctrl).ValueMember = dbcolID;

        ((ComboBox)cbctrl).DisplayMember = dbcol;

        ((ComboBox)cbctrl).Items.Insert(0, string.Empty);

     

        thisConnection.Close();

    }

    Monday, May 22, 2006 7:10 PM
  • Hi there,

    I'm joining you a little late but as I see it, your problem is that the combo box initially has a selected value, which is the first value in the list but you don't want an item selected initially.

    As the errors you are getting show, you can't mess with the items in a bound combo box. However, if you put the following code right before the end of your function:

    ((ComboBox) cbtrl).SelectedIndex = -1

    I believe that this will set it so that no value is initially selected. Later, when you have to build your search query, you can test for the selected index in the combo box and if it's < 0 then you know nothing's selected and you can exclude a condition from your search.

    Also, where are you calling FillComboBoxControl() from? If you are calling it from your form's Load() handler then it's also feasible to set the SelectedIndex property to -1 in the last statement before the end of the Load() handler.

    Hope that helps a bit, but sorry if it doesn't
    Wednesday, May 24, 2006 7:25 AM
  • Thanks that helped a ton.  That uncomplicates what I was in the middle of quite a bit.  I like the idea with the Load() handler too!  That's getting built in for sure.

    Thanks again for the help.

    Wednesday, May 24, 2006 8:00 AM
  • Nate,

    I believe that the selected index = -1 does not work for data- bounded comboboxes.

    http://msdn2.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex.aspx

    "To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item."
    Monday, July 10, 2006 6:01 PM
  • This is the exact problem i have with the ComboBox as well. Any suggestion without placing a hard blank item into the data source?
    Monday, September 18, 2006 6:23 AM
  • You can always resort to the brute force method.  Ignoring database constraints like foreign keys, non-nullable fields, etc., after setting the selected index to -1, you can update the dataview directly.  The code snippet below assumes you are using a CurrencyManager object to track the position within you data source.

    private void ComboBox_Leave(object sender, System.EventArgs e)

    {

    if (sender.GetType() == typeof(System.Windows.Forms.ComboBox))

    {

    ComboBox cb = (ComboBox)sender;

    if (cb.Text == string.Empty)

    {

    cb.SelectedIndex = -1;

    DataView dv = myDataSet.Tables[0].DefaultView;

    dv[myBindingManager.Position]["FieldName"] = null;

    }

    }

    }

    By placing this code in the ComboBox's Leave event handler (and your combobox's dropdown style is type DropDown) it will allow the end-user to clear the combobox value and save the data.  Again, based on your database constraints, you may be able to set the fields value to String.Empty or virtually any value.  I have a foreign key constraint and was forced to set my value to null.

    Hope this helps,

    Phil

    Wednesday, September 27, 2006 1:25 AM
  •  

    To unselect the combobox when the combo contains data-bound items you can write these 2 lines.

     

    mycombo.SelectedIndex =0  ' selects the firs item on the list

    mycombo.SelectedIndex =-1 ' for some reazon now the combo is able to unselected the item.

     

    Regards

    Horacio

    Friday, October 17, 2008 7:51 PM
  • Horacio:

     

    That approach indeed works. And what good timing. You posted this solution less than 2 weeks ago, and I desperately needed it today.

     

    I'm glad you solved your problem, and I appreicating your helping me.

     

    Sunday, November 2, 2008 7:05 PM
  • Ok - a lot of useful information here on this problem.  I have two related questions:

     

    1. If the ComboBox is DropDownStyle = ComboBoxStyle.DropDownList which only allows the user to select from a fixed list of items, is there any way for the user to clear the comboBox?  I don't think so.

     

    2. If the comboBox is a column in a DataGridView is there any way for the user to clear the ComboBox?  It appears that DataGridView uses DropDownStyle = ComboBoxStyle.DropDown for the editing control, but when the user blanks the combo, the grid puts the value back.

     

    If the only solution is to change my ComboBox-Populating query to include a blank row, this stinks.  There should be a simple setting for a ComboBox that indicates whether the user will be allowed to blank the value of the combo.  I shouldn't have to change all my data sources to include a blank row.

    Thursday, November 20, 2008 9:10 PM
  • Does anyone have an answer to this yet ?

    If the combo is databound, and DropdownStyle = DropDownList, how to unselect it ? Both -1 and 0 throw an exception !

    Surely this is not rocket science.
    Tuesday, August 25, 2009 7:39 AM
  • I think you should do that
    1 create function that return dataset
    for example qry is: "select Student_code, Student_name from TableStudent"
    in this example ds contain value of query

    dim dt as datatable  = ds.table(0)
    dt.rows.add( new object() {"0", "------All------"})
    comboboxName.DataSource = dt
    comboboxName.ValueMember = "Student_code"
    comboboxName.DisplayMember = "Student_Name"


    I sure you will success
    Saturday, December 5, 2009 5:14 PM
  • I think you should do that
    1 create function that return dataset
    for example qry is: "select Student_code, Student_name from TableStudent"
    in this example ds contain value of query

    dim dt as datatable  = ds.table(0)
    dt.rows.add( new object() {"0", "------All------"})
    comboboxName.DataSource = dt
    comboboxName.ValueMember = "Student_code"
    comboboxName.DisplayMember = "Student_Name"
    Saturday, December 5, 2009 5:15 PM
  • I am sory, my solution is mistake
    Saturday, December 5, 2009 5:31 PM
  • Hi there,

    I'm joining you a little late but as I see it, your problem is that the combo box initially has a selected value, which is the first value in the list but you don't want an item selected initially.

    As the errors you are getting show, you can't mess with the items in a bound combo box. However, if you put the following code right before the end of your function:

    ((ComboBox) cbtrl).SelectedIndex = -1

    I believe that this will set it so that no value is initially selected. Later, when you have to build your search query, you can test for the selected index in the combo box and if it's < 0 then you know nothing's selected and you can exclude a condition from your search.

    Also, where are you calling FillComboBoxControl() from? If you are calling it from your form's Load() handler then it's also feasible to set the SelectedIndex property to -1 in the last statement before the end of the Load() handler.

    Hope that helps a bit, but sorry if it doesn't

    I did not know you could do this, WOW thanks!!!!!
    Tuesday, July 13, 2010 2:19 PM
  • Hi,

    I too was searching for an answer to this question. I solved it by using a union query (I'm running MYSQL, not sure if this works on other db providers)

    SELECT 0 as supplier_no, '' AS supplier_name UNION SELECT supplier_no, supplier_name FROM supplier ORDER BY supplier_name

    This gave me a blank row at the top of my combobox (which was selected by default) and means I don't have to add any garbage data into my database.

    Hope it helps anyone else finding this.

    Thanks,
    Paul

    Tuesday, August 4, 2020 5:47 PM