Get checkbox.checked value programmatically from a loop through winform controls

In my winforms program, I have a Options dialog box, and when it closes, I look at all the names of the dialog box controls (text fields, check boxes, etc.) and their values ​​and save them in the database so that I can read from him in my program. As you can see below, I can easily access the Text property from the Control group, but there is no property to access the Checked value of the text field. Do I need to convert c in this case to a checkbox?

 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 do this?

+2
source share
4 answers

Yes, you need to convert it:

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

And you can simplify the reading:

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

Robert's answer is good, but let me give you the best

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

You can use in place:

 controlVal = (CheckBox)c.Checked; 

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

-1
source

try the following:

 controlVal = Convert.ToString(c.Checked); 
-1
source

Source: https://habr.com/ru/post/951223/


All Articles