This is a migrated thread and some comments may be shown as answers.

Add new value to data source

1 Answer 117 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Justin
Top achievements
Rank 1
Justin asked on 02 Nov 2010, 11:38 PM
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

1 Answer, 1 is accepted

Sort by
0
Accepted
Emanuel Varga
Top achievements
Rank 1
answered on 05 Nov 2010, 02:29 PM
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
Tags
DropDownList
Asked by
Justin
Top achievements
Rank 1
Answers by
Emanuel Varga
Top achievements
Rank 1
Share this question
or