简体   繁体   中英

Get checkbox.checked value programmatically from cycling through winform controls

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 Text property from the Control group, but there's no property to access the Checked value of the textbox. Do I need to convert c , in that instance, to a checkbox first?

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 c first, how do I go about doing that?

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(); 

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;
}

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 = Convert.ToString(c.Checked);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM