复选框未按预期工作
我的表单中有三个复选框。问题是,当我检查所有三个时,我只收到一个复选框。我该如何解决这个问题?
我的代码:
private void button1_Click(object sender, EventArgs e)
{
ConfigOptions itemToSave = 0;
if (autoCapsNames.Checked)
{
itemToSave |= ConfigOptions.AutoCapsStr;
}
if (autoSort.Checked)
{
itemToSave |= ConfigOptions.IntantOrganization;
}
if (showLinesNumbers.Checked)
{
itemToSave |= ConfigOptions.ShowLinesNumber;
}
SaveConfigs(itemToSave);
}
谢谢
I have three checkboxes in my form. The problem is that when I check all three, I only received one checkbox. how can I fix this?
my code:
private void button1_Click(object sender, EventArgs e)
{
ConfigOptions itemToSave = 0;
if (autoCapsNames.Checked)
{
itemToSave |= ConfigOptions.AutoCapsStr;
}
if (autoSort.Checked)
{
itemToSave |= ConfigOptions.IntantOrganization;
}
if (showLinesNumbers.Checked)
{
itemToSave |= ConfigOptions.ShowLinesNumber;
}
SaveConfigs(itemToSave);
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
前面的答案应该可以解决您的问题,但它改变了您处理数据的方式。
如果您想使用按位 OR 方法(就像您现在所做的那样),请确保您已正确定义
ConfigOptions
。分配给ConfigOptions.AutoCapsStr
、ConfigOptions.IntantOrganization
和ConfigOptions.ShowLinesNumber
的值应以这样的方式选择,以定义您在独特的方式。如果
ConfigOptions
是一个enum
,您可以尝试像这样定义它:然后,您可以在
SaveConfigs
方法中使用它(或者在您的加载方法,如果您只保存数值)来测试设置的值,如下所示:The previous answer should solve your issue, but it changes the way you handle the data.
If you want to use bitwise OR method (as you are doing now), make sure you have correctly defined
ConfigOptions
. Values assigned toConfigOptions.AutoCapsStr
,ConfigOptions.IntantOrganization
andConfigOptions.ShowLinesNumber
should be chosen in such a way to define the values you set in a unique way.If
ConfigOptions
is anenum
, you can try to define it like this:Then, you can use it inside your
SaveConfigs
method (or in your loading method, if you just save the numeric value) to test values set like this:您的代码可能只设置
itemToSave
一次。如果选中所有复选框,则最终可能只保存showLineNumbers
,因为您通过每个 if 语句覆盖了 itemToSave。您可能想稍微改变一下您的方法。您可以
if
语句中SaveConfigs(itemToSave);
内部,从而单独保存每个配置选项。itemToSave
存储在List
中,并循环遍历列表,最后保存您需要的内容。这是一种快速而肮脏的方法来帮助您开始。
或者,如果您要在按位计算中使用 int ,请参阅@Lucas 的答案。我个人从来没有这样做过,但他有一个很好的观点。 (我今天学到了一些东西)。
Your code might only be setting the
itemToSave
once. If all your checkboxes are checked, you could end up only savingshowLineNumbers
since you're overwriting itemToSave through every if statement.You might to want to change your approach a little. You could
SaveConfigs(itemToSave);
inside eachif
statement, thereby saving each config option individually.itemToSave
inside aList<T>
, and loop through the list, saving what you need at the end.Here's a quick and dirty approach to get you started
Alternatively if you're going to use
int
's in a bitwise calculation, please see @Lucas's answer. I've personally never done it that way, but he has a great point. (I've learned something today).