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

后端 未结 13 1319
谎友^
谎友^ 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:13
    cmbHierarchies.SelectedIndex = -1;
    
    0 讨论(0)
  • 2020-12-14 09:14

    There are two things you can do:

    1. Add an empty row to the DataTable that is returned from the stored procedure.

      DataRow emptyRow = hierarchies.NewRow();
      emptyRow["guid"] = "";
      emptyRow["ObjectLogicalName"] = "";
      hierarchies.Rows.Add(emptyRow);
      

      Create a DataView and sort it using ObjectLogicalName column. This will make the newly added row the first row in DataView.

      DataView newView =           
           new DataView(hierarchies,       // source table
           "",                             // filter
           "ObjectLogicalName",            // sort by column
           DataViewRowState.CurrentRows);  // rows with state to display
      

      Then set the dataview as DataSource of the ComboBox.

    2. If you really don't want to add a new row as mentioned above. You can allow the user to set the ComboBox value to null by simply handling the "Delete" keypress event. When a user presses Delete key, set the SelectedIndex to -1. You should also set ComboBox.DropDownStyle to DropDownList. As this will prevent user to edit the values in the ComboBox.

    0 讨论(0)
  • 2020-12-14 09:15

    I would bind the data then insert an blank item at position 0 using the ComboxBox.Items.Insert method. Similar to what flipdoubt suggested, but it adds the item to the top.

    0 讨论(0)
  • 2020-12-14 09:20

    Cant you add a new DataRow to the DataTable before you bind it to your DataSource?

    You can use the NewRow function of the DataTable to achieve this:

    http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx

    0 讨论(0)
  • 2020-12-14 09:21

    Er, can't you just add a default item to the ComboBox after data binding?

    0 讨论(0)
  • 2020-12-14 09:24

    insert a blank row in your datatable, and check for it in validation/update/create

    0 讨论(0)
提交回复
热议问题