我是在Visual Studio和C#中创建表单的新手。但是我做了一个UI,它有一些组合框,其中的DropDownStyle是DropDownList。显示的项目为Yes和No。但我需要将它作为布尔值分配给某个对象ai上的属性,并且当前这样做:
if (cmbExample.Text == "Yes")
{
ai.isPacketType = true;
}
else if (cmbExample.Text == "No")
{
ai.isPacketType = false;
}我基本上想做一些类似这样的事情(或其他一些内联程序):
ai.isPacketType = cmbExample.Text;如何将文本Yes链接到true,将No链接到false?
发布于 2010-11-25 16:48:49
你可以这样做:
ai.isPacketType = (cmbExample.Text == "Yes");或者如果isPacketType为bool?
ai.isPacketType = string.IsNullOrEmpty(cmbExample.Text) ? (bool?)null : cmbExample.Text == "Yes";发布于 2011-01-15 01:50:54
如果您想要这样做,并且您正在使用数据绑定,那么有一种在this blog post中描述的简洁的小方法可以实现。基本上,您设置了几个键值对:
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;
}或者在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并绑定到这组对。有关详细信息,请访问博客链接。
发布于 2010-11-25 16:48:58
ai.isPacketType = (cmbExample.Text == "Yes");https://stackoverflow.com/questions/4275126
复制相似问题