First of all, in you want to deal with nullable index, you should not deal with function returning
int
, you should use only the function returning
int?
. Basically, your code of
SelectedPicklistNullableID
is correct. The only problem is: will the item really of the type
PickListItem
? It is not shown in your code, but it would be a good idea. But then, you should not use
int?
type at all. The null value is actually not the
ID
, but the whole record you store in the list item. You don't need your
Selected*
method(s) either.
Here is what you can do:
class PickListItem {
internal int ID { get; set; }
}
cb.Items.Add(new PickListItem());
btnSave.Click += (sender, eventArgs) => {
PickListItem item = (PickListItem)cb.SelectedItem;
if (items == null) return;
CaseRecord.CaseStatusID = item.ID;
};
You can do even better. Make your
btnSave
disable at first. Handle the event
System.Windows.Forms.ComboBox.SelectedIndexChanged
and, when some valid element in the list is selected, assign
btnSave.Enabled = true
. It will simply prevent doing "save" when you don't have properly selected element.
Now, everything is fine here, with one problem: the UI will show something like "My.Namespace.Name.PickListItem". How to show something useful instead. Simple! What is shown is based on the value returned by
System.Object.ToString
. Override it! It could be something like
class PickListItem {
public override string ToString() {
return string.Format("Item {0}", ID);
}
internal int ID { get; set; }
}
Please see my past answer:
combobox.selectedvalue shows {} in winform[
^].
Are you getting the idea?
—SA