Get checkbox.checked value programmatically from c

2019-08-05 21:16发布

问题:

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?

回答1:

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


回答2:

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


回答3:

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.



回答4:

try this:

controlVal = Convert.ToString(c.Checked);