我正在继续我之前的问题,因为我从未得到完整的答复。引用循环中创建的上一个对象以更新 SQL
基本上,我已将语法更改为以下内容,但是它有两个问题:
- 复选框实际上并没有出现。
- 在 saveOrderBtn_Click 循环中,我收到错误消息“当前上下文中不存在名称‘myBoxes’”。这是在“if”语句行上。
我不能使用 Controls.Add(myCheckBox); 当您进行更新时,这会根据循环中创建的最后一个复选框更新 SQL 中的所有内容 - 它不计算每个复选框。
我还在学习 C#。非常感谢您。
更新代码:
public partial class SelectUsers : Form {
// DECLARE THE myCheckBox
private CheckBox myCheckBox;
public SelectUsers()
{
InitializeComponent();
}
private void SelectUsers_Load(object sender, EventArgs e)
{
DataSet ds = myconnection.runSelect(new DataSet(), "THE SELECT");
int xAxisCheckbox = 40;
int yAxisCheckbox = 50;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
// CHANGED List<CheckBox> myBoxes LINE
List<CheckBox> myBoxes = new List<CheckBox>();
myCheckBox = new CheckBox();
myCheckBox.Location = new Point(xAxisCheckbox, yAxisCheckbox);
myCheckBox.Size = new Size(120, 20);
myCheckBox.Text = ds.Tables[0].Rows[i]["FullName"].ToString();
myCheckBox.Checked = (bool)ds.Tables[0].Rows[i]["InOperation"];
yAxisCheckbox = yAxisCheckbox + 80;
// THIS SHOULD ADD/RENDER EACH CHECKBOX, BUT IT DOESN'T
myBoxes.Add(myCheckBox);
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
DataSet ds = myconnection.runSelect(new DataSet(), "THE SELECT");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
userID = (int)ds.Tables[0].Rows[i]["UserID"];
if (myBoxes[i].Checked)
{
myconnection.runUpdate("UPDATE Users SET InOperation = 1, OperationOrder = CASE WHEN OperationOrder = 1 THEN 1 ELSE CASE WHEN InOperation=1 THEN OperationOrder ELSE (SELECT COUNT(*)+1 FROM Users WHERE InOperation=1 AND OperationOrder > 0) END END WHERE UserID=" + userID);
myconnection.runUpdate("UPDATE Users SET OperationOrder = CASE WHEN OperationOrder = 0 THEN (SELECT COUNT(*) FROM Users WHERE InOperation=1) ELSE OperationOrder END WHERE InOperation=1");
}
else
{
myconnection.runUpdate("UPDATE Users SET InOperation = 0, OperationOrder = 0 WHERE UserID=" + userID);
myconnection.runUpdate("UPDATE Users SET OperationOrder = CASE WHEN OperationOrder -1 = 0 THEN (SELECT COUNT(*) FROM Users WHERE InOperation=1) ELSE OperationOrder -1 END WHERE InOperation=1");
}
}
}
}