How can I make a Yes/No combobox return true/false?
I am new to creating forms in Visual Studio and C#. But I made a UI that has some comboboxes where the DropDownStyle is DropDownList. The items shown is Yes and No. But I need to assign this as a boolean value to a property on some object ai and currently do this:
if (cmbExample.Text == "Yes")
{
ai.isPacketType =开发者_JS百科 true;
}
else if (cmbExample.Text == "No")
{
ai.isPacketType = false;
}
I basically want to do something like this (or some other one liner):
ai.isPacketType = cmbExample.Text;
How do I link the Text Yes to the value true and No to false?
You can do it like this:
ai.isPacketType = (cmbExample.Text == "Yes");
Or if isPacketType
is bool?
:
ai.isPacketType = string.IsNullOrEmpty(cmbExample.Text) ? (bool?)null : cmbExample.Text == "Yes";
If you want to do this and you're using databinding there's a neat little way to do it described in this blog post. Basically you set up a couple of key value pairs:
private List<KeyValuePair<string, bool>> GenerateYesNo()
{
List<KeyValuePair<string, bool>> yesNoChoices = new List<KeyValuePair<string,bool>>();
yesNoChoices.Add(new KeyValuePair<string, bool>("Yes", true));
yesNoChoices.Add(new KeyValuePair<string, bool>("No", false));
return yesNoChoices;
}
Or in VB.Net:
Private Function GenerateYesNo() As List(Of KeyValuePair(Of String, Boolean))
Dim yesNoChoices As New List(Of KeyValuePair(Of String, Boolean))
yesNoChoices.Add(New KeyValuePair(Of String, Boolean)("Yes", True))
yesNoChoices.Add(New KeyValuePair(Of String, Boolean)("No", False))
Return yesNoChoices
End Function
and bind to this set of pairs. For full details follow the blog link.
ai.isPacketType = (cmbExample.Text == "Yes");
You can of course write it like this
ai.isPacketType = cmbExample.Text == "Yes";
Ideally you probably want to create a little wrapper class/struct around Boolean. You can then override the ToString() value to return either Yes or No.
The underlying value will stay the same, but the UI will display a different value by using the ValueMember and DisplayMember properties on a ComboBox.
This would probably be considered an MVVM approach, by adding a ViewModel on your data for making it look good on the UI, without driving it directly with any conditional code.
You could either use ai.isPacketType = cmbExample.Text == "Yes"
(case sensitive), or ai.isPacketType = string.Compare(cmbExample.Text, "Yes", true) == 0
(case insensitive).
Cant you use the 'Checked' property, which will give you true is checked and false if unchecked:
ai.isPacketType = cmbExample.Checked;
精彩评论