如果组合框所选索引 = 0,则设置 null



我有一个简单的模型,如下所示:

public class NoteModel
{
public Guid? DesignGroupId { get; set; }
public int? ProjectKey { get; set; }
public int? DesignKey { get; set; }
}

所以我想设置这样的模型:

NoteModel model = new NoteModel();

该属性取决于所选组合框选择的值,因此我需要执行以下操作:

if(cboDesignGroup.SelectedIndex != 0)
{
model.DesignGroupId = Guid.Parse(cboDesignGroup.SelectedValue.ToString());
}

因此,每个属性都有一个 if 子句,具体取决于他的下拉列表。如果组合框 = 0,那么只是空,因为我从未设置过它。

有没有另一种方法可以做到这一点更干净和可读?问候

如果您努力很好地填充列表框,它将使其他地方的代码更好。此示例使用 c# 7 ValueTuple,但您可以使用 Tuple,或者仅使用字符串和 Guid 创建自己的类?财产

var items = new List<(string, Guid?)>();
items.Add(("No selection", (Guid?)null));
items.Add(("Option 1", (Guid?)Guid.NewGuid()));
items.Add(("Option 1", (Guid?)Guid.NewGuid()));

如上所述声明的 ValueTuple 具有一个属性.Item1,该属性是一个字符串(用于在组合中显示(和一个.Item2,该属性是一个Nullable<Guid>(用于插入到模型(。您可以通过绑定将项目放入组合中:

yourcombo.DataSource = items;
yourcombo.DisplayMember = "Item1"; //string name of property to call to get display text -> the ValueTuple.Item1
yourcombo.DisplayMember = "Item2"; //name of property to use as value

然后,在用户做出选择(包括"无选择",列表中的第一项(后,只需将comboBox.SelectedValue分配给模型:

model.DesignGroupId = (Guid?)yourcombo.SelectedValue;

组合没有"空白"状态;这就是为什么第一项是"(无选择(",并且它的值类型为 Guid? 和值"null";它可以像任何其他 Guid 一样直接分配给您的模型? 有一个值

这里没有"if selectedindex"等;填充模型实际上只是将组合的SelectedValue直接分配到模型中。让它比这更干净的唯一方法是将模型属性数据绑定到组合,可能如下所示:

yourcombo.DataBindings.Add("SelectedValue", model, "DesignGroupId");

然后,每次组合失去焦点时,它都会将当前选定的值戳入model.DesignGroupId

:)


如果你没有 c#7,那么你可以使用元组:

private void Form1_Load(object sender, EventArgs e)
{
var l = new List<Tuple<string, Guid?>>();
l.Add(Tuple.Create("No sel", (Guid?)null));
l.Add(Tuple.Create("opt 1", (Guid?)Guid.NewGuid()));
l.Add(Tuple.Create("opt 2", (Guid?)Guid.NewGuid()));
comboBox1.DataSource = l;
comboBox1.DisplayMember = "Item1";
comboBox1.ValueMember = "Item2";
}
private void button1_Click(object sender, EventArgs e)
{
model.Whatever = (Guid?)comboBox1.SelectedValue;
}

或者你可以使用自己的类,尽管这是Tuple被发明的那种东西,所以你周围没有无数的小类,这些类只不过是几个基元的配对。

首先,您的代码建议,如果在组合框中选择了除第一个元素之外的任何元素,则设置 guid。

0 实际上是一个有效的索引,因为组合框是一个零绑定索引。(0 是第一个元素,1 是第二个元素,依此类推(。

你想依赖 selectedIndex,你应该写这样的东西:

if(cboDesignGroup.SelectedIndex > -1)
{
model.DesignGroupId = Guid.Parse(cboDesignGroup.Items[cboDesignGroup.SelectedIndex].ToString());
}
//Depending of which framework you are using (WPF, WinForms etc), you could write something like this:
//WPF & WinForms:
if (cboDesignGroup.SelectedItem != null)
model.DesignGroupId = Guid.Parse(cboDesignGroup.SelectedItem.ToString());

//Or you could do something like this:
m.DesignGroupId = (cboDesignGroup.SelectedItem == null ? null : (Guid?)Guid.Parse(cboDesignGroup.SelectedItem as string));

最新更新