在组合框中设置所选值的最佳方法是什么? [英] what is the best way how to set selected value in combo box?

查看:84
本文介绍了在组合框中设置所选值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,什么是更好的解决方案,为什么?

我想第二个,作为异常应该在代码中只是为了处理错误而这不是错误(只是值不在组合框中)?我对吗?这是唯一的原因吗?或者两种解决方案都没有错?

还是有其他解决方案吗?比这两个好吗?



I''m wondering, what is better solution and why?
I suppose that the second one, as exception should be in the code just to handle errors and this is not an error (just the value is not in combo box)? Am I right? And is it the only reason? Or there''s nothing wrong about both solutions?
Or is there another solution? Better than these two?

try
{
   cbOwner.SelectedValue = whatever.toString();
}
catch (Exception ex)
{
   //nothing happened, program can continue
}






or

if (cbOwner.Items.FindByValue(whatever.toString()) != null)
   cbOwner.SelectedValue = whatever.toString();

推荐答案

你展示的是真的糟糕的方式,因为你可能很容易犯一个字符串的错误。因此,设置所选索引要好得多(确切答案取决于 ComboBox 的确切类型;此名称下有不同类型)。



但真正强大而可靠的方法是将一些语义数据类型的项目放入列表中。我在过去收集的答案中解释了这一点:

combobox。 selectedvalue在winform中显示{} [ ^ ]。



-SA
What you show is a really bad way, because you may easily make a mistake with a string. Therefore, it''s much better to set selected index (exact answer depends on exact type of ComboBox; there are different types under this name).

But really robust and reliable approach is to put items of some semantic data type in the list. I explain it in my past answers collected here:
combobox.selectedvalue shows {} in winform[^].

—SA


有类似的问题讨论并且许多人在asp.net论坛中提供了解决方案: C#如何分配组合框值/文本 [ ^ ]
There was a similar problem discussed and many people provided solutions in the asp.net forum: C# How To Assign Combo Box Values / Text[^]


这篇关于在组合框中设置所选值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆