复选框上的多重控制 [英] Multiple Control on Checkbox
问题描述
大家好,
我有一个带八个复选框的表格。
我的意图是控制是否选中了复选框,所以我使用了以下代码:
Hi everyone,
I have a form with eight checkbox.
My intention is to control if the checkbox is checked, so I used this code:
if(cbMouse.Checked == true)
{
//do something
}
选中复选框时我想要将复选框的名称插入sql参数。
例如:
When checkbox is checked I want to insert the checkbox's name into a sql parameter.
For example:
if(cbMouse.Checked == true)
{
string query = "INSERT INTO TEST (things) VALUES (@things)";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add("@things", cbMouse.Text.ToUpper());
我的问题是:如何对八个复选框进行多重控制并将复选框的名称插入一个sql参数(@things)?
My question is: how I can do a multiple control for eight checkbox and insert checkbox's name into a single sql parameter (@things) ?
推荐答案
您好,
放置面板控件(将其命名为panThings)在您的表单上,然后将您的复选框移动到该面板以对它们进行分组。
然后使用此代码:
Hello,
Put Panel control (name it panThings) on your form and then move your checkboxes to that panel to group them.
Then use this code:
var things = string.Join(",", panThings.Controls.OfType<CheckBox>().Where(x => x.Checked).Select(x => x.Text.ToUpper()));
string query = "INSERT INTO TEST (things) VALUES (@things)";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add("@things", things);
不要忘记将 System.Linq 添加到使用文件顶部的子句。
[更新1]
假设您有带文本的复选框:
鼠标,键盘,硬盘,显示器等。
然后,如果你检查即鼠标和监视器复选框输出将是:
And don't forget to add System.Linq to your using clause at top of the file.
[Update 1]
Suppose that you have checkboxes with texts:
Mouse, Keyboard, Hard drive, Monitor and so on.
Then if you check i.e. Mouse and Monitor checkboxes output will be:
Mouse,Monitor
该值将存储在数据库中。
[更新2 - 回复评论]
要恢复所选项目,请执行以下操作:
And that value will be stored in DB.
[Update 2 - Answer to comment]
To restore selected items do this:
// Get your thing from DB
var thingsFieldValue = dt.Rows[0]["PUT_YOUR_THINGS_DB_FIELD_NAME_HERE"].ToString();
// Split them and store in string[] (array of string)
var things = thingsFieldValue.Split(",".ToCharArray());
// Iterate through all elements in array
foreach (var thing in things)
{
// Find proper CheckBox control
var checkBox = panThings.Controls.OfType<CheckBox>().Where(x => x.Text.ToUpper() == thing).FirstOrDefault();
// If checkbox was found, set its Checked property
if (checkBox != null)
{
checkBox.Checked = true;
}
}
干杯!
Cheers!
这篇关于复选框上的多重控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!