How to insert 'Empty' field in ComboBox bound to DataTable

后端 未结 13 1317
谎友^
谎友^ 2020-12-14 09:07

I have a combo box on a WinForms app in which an item may be selected, but it is not mandatory. I therefore need an \'Empty\' first item to indicate that no value has been s

13条回答
  •  时光说笑
    2020-12-14 09:30

    Instead of adding a new row to your datatable, just bind the data to the combobox and at load set the SelectedIndex to -1. This will cause the selection to be null until the user selects an item.

    I clipped this from one of my current projects.

            Attorney_List_CB.DataSource = DA_Attorney_List.BS.DataSource;
            Attorney_List_CB.DisplayMember = "Attorney Name";
            Attorney_List_CB.SelectedIndex = -1;      
    

    In order to clear the selection I usually insert a button that sets the SelectedIndex back to -1.

        private void Clear_Selection_BTN_Click(object sender, EventArgs e)
        {
            Attorney_List_CB.SelectedIndex = -1;  // Clears user selection
        }
    

    Finally, once I validate the data on my form, if the SelectedIndex of any combobox is -1 then it is skipped, or I will generate some type of default value such as "N/A" or whatever I need under the circumstances.

提交回复
热议问题