Add new value to data source

2 posts, 1 answers
  1. Justin
    Justin avatar
    35 posts
    Member since:
    Apr 2008

    Posted 02 Nov 2010 Link to this post

    Hey, not sure if I am missing something here, but I am not finding any way to add a new value to the underlying data source when user types a value into the drop down list that does not currently exist. 

    I mean, I have my own code that will handle this, I am jsut trying to determine the best time to do what is needed - if the user types in a value that does not exist in data bound list would it make sense to have the code in the TextChanges event, in the Validating event, or somewhere else?

    Thanks!

    Justin
  2. Answer
    Emanuel Varga
    Emanuel Varga avatar
    1336 posts
    Member since:
    May 2010

    Posted 05 Nov 2010 Link to this post

    Hello,

    You can handle the SelectedValueChanged event and do something like this:
        var list = new List<string> { "aaa", "bbb", "ccc" };
        radDropDownList1.DataSource = list;
        radDropDownList1.SelectedValueChanged += new System.EventHandler(radDropDownList1_SelectedValueChanged);
     
    void radDropDownList1_SelectedValueChanged(object sender, System.EventArgs e)
    {
        if (radDropDownList1.SelectedValue == null)
        {
            var selectedText = radDropDownList1.SelectedText;
            var iListDataSource = radDropDownList1.DataSource as IList;
            if (iListDataSource != null)
            {
                iListDataSource.Add(selectedText);
                radDropDownList1.Rebind();
                radDropDownList1.SelectedValue = selectedText;
            }
        }
    }
    If the selectedValue = null, then the item is not in the list, so add it. You should also check for string.Empty, and maybe some other validations if required.

    Hope this helps, if you have any other questions or comments, please let me know,

    Best Regards,
    Emanuel Varga
  3. UI for WinForms is Visual Studio 2017 Ready
Back to Top