简体   繁体   中英

Pass a value if a checkbox is checked

I have a form that has some textboxes (45) with CheckBoxes next to each, and a button. When the button is pressed I want to pass the values of each Textbox that has a checked CheckBox to a void in another class and the ones that are not checked pass a null value.

What I have at the moment is: Form1

private void button_Click(object sender, EventArgs e)
{
String Value1;
if (value1CheckBox.Checked)
{
    Value1 = value1TextBox.Text;
}
else
{
    Value1 = null;
}

String Value2;
if (value2CheckBox.Checked)
{
    Value2 = value1TextBox.Text;
}
else
{
    Value2 = null;
}

etc...

Form2 form2 = new Form2();
form2.insertSQL(Value1, Value2, etc...);
}

Form2

private void insertSQL(String Value1, String Value2, String etc...)
{
    /*
    Code to insert to SQL database
    */
}

But that seams very inefficient and I'm sure there must be a better way to pass the values if the boxes are checked. Any advice on a better way to do this would be appreciated, also sorry if I have used the wrong terminology I am very new to programing.

A good idea would be to store all your check boxes and text boxes into a Dictionary. The particular dictionary you would need to create would be:

Dictionary checkToText = new Dictionary();

Then, put each CheckBox/TextBox pair mapping into the dictionary.

Finally, in the button_Clicked method, create a loop that loops through each key/value pair in your dictionary:

foreach (KeyValuePair<CheckBox, TextBox> pair in checkToText)
{
//do what you need to do
//pair.Key for checkbox
//pair.Value for textbox
}

I think the limitation you are getting at is that unchecked checkboxes do not get passed as part of a form post.

You can assemble a javascript that, onclick, will assemble some JSON and put it into a hidden value, then deserialize the JSON from the hidden value (in your server code). That will allow you to set null for the textboxes without having to loop over the form fields on the server-side.

Maintainability is going to be driver for your decision whether to punt this to the server-side or do it on the client-side, like I've described.

Also, don't forget to clean the data before creating SQL (as your server-side function name suggests). You can't trust that data!

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