且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

复选框上的多重控制

更新时间:2023-10-06 21:10:28

您好,



放置面板控件(将其命名为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!