C# 从循环通过 winform 控件以编程方式获取 checkbox.checked 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18103783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:17:57  来源:igfitidea点击:

Get checkbox.checked value programmatically from cycling through winform controls

c#winformscheckboxtextbox

提问by gnarlybracket

For my winforms program, I have an Options dialog box, and when it closes, I cycle throught all the Dialog Box control names (textboxes, checkboxes, etc.) and their values and store them in a database so I can read from it in my program. As you can see below, I can easily access the Textproperty from the Controlgroup, but there's no property to access the Checkedvalue of the textbox. Do I need to convert c, in that instance, to a checkbox first?

对于我的 winforms 程序,我有一个选项对话框,当它关闭时,我循环查看所有对话框控件名称(文本框、复选框等)及其值并将它们存储在数据库中,以便我可以从中读取我的程序。正如您在下面看到的,我可以轻松地TextControl组中访问该属性,但没有可以访问Checked文本框值的属性。c在这种情况下,我是否需要先将转换为复选框?

conn.Open();
foreach (Control c in grp_InvOther.Controls)
{
    string query = "INSERT INTO tbl_AppOptions (CONTROLNAME, VALUE) VALUES (@control, @value)";
    command = new SQLiteCommand(query, conn);
    command.Parameters.Add(new SQLiteParameter("control",c.Name.ToString()));
    string controlVal = "";
    if (c.GetType() == typeof(TextBox))
        controlVal = c.Text;
    else if (c.GetType() == typeof(CheckBox))
        controlVal = c.Checked; ***no such property exists!!***

    command.Parameters.Add(new SQLiteParameter("value", controlVal));
    command.ExecuteNonQuery();
}
conn.Close();

If I need to convert cfirst, how do I go about doing that?

如果我需要先转换c,我该怎么做?

采纳答案by Mario Sannum

Yes, you need to convert it:

是的,你需要转换它:

else if (c.GetType() == typeof(CheckBox))
    controlVal = ((CheckBox)c).Checked.ToString(); 

And you can make the check simpler to read:

您可以使支票更易于阅读:

else if (c is CheckBox)
    controlVal = ((CheckBox)c).Checked.ToString(); 

回答by Alex

You can cast in place:

您可以就地投射:

controlVal = (CheckBox)c.Checked;

BTW: controlVal does not need to be a string, a boolean will do the job and save memory.

顺便说一句: controlVal 不需要是一个字符串,一个布尔值将完成这项工作并节省内存。

回答by Fahad Murtaza

try this:

尝试这个:

controlVal = Convert.ToString(c.Checked);

回答by No Idea For Name

robert's answer is good but let me give you a better one

罗伯特的回答很好,但让我给你一个更好的

TextBox currTB = c as TextBox;
if (currTB != null)
    controlVal = c.Text;
else
{
    CheckBox currCB = c as CheckBox;
    if (currCB != null)
    controlVal = currCB.Checked;
}