[英]C# - Using Windows Forms Applications and SQL Server; Check boxes and Groupboxes
我正在尝试使用C#和SQL Server 2012创建Windows Form App。
我的应用程序有两个文本框,一个按钮和三个组框,每个组框具有三个复选框。 我希望应用程序获取选中的复选框的值,并将所有数据保存到SQL Server中的一行。
例:
ID int PK not null,
Customer_Name varchar(50)
Item_Name nvarchar(max) null
Item_Model nvarchar(max) null
Item_Color nvarchar(max) null
我已经为窗体创建了3个Group框,每个都有3个复选框:
GroupBox1:
CheckBox1 - name : chkboxLaptop
CheckBox2 - name : chkboxDesktop
CheckBox1 - name : chkboxMonitor
GroupBox2:
CheckBox1 - name : chkboxDell
CheckBox2 - name : chkboxHp
CheckBox1 - name : chkboxLenovo
GroupBox3:
CheckBox1 - name : chkboxSilver
CheckBox2 - name : chkboxGrey
CheckBox1 - name : chkboxBlack
我希望Demo_Table表看起来像这样:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop Lenovo Black
这是我的代码:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conString);
StringBuilder name = new StringBuilder();
foreach (Control ctrl in this.groupBox1.Controls)
{
if (ctrl is CheckBox)
{
if (((CheckBox)ctrl).Checked == true)
{
name.Append(((CheckBox)ctrl).Text.ToString() + " ");
con.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO Demo_Table (ID,Customer_Name,Item_Name) VALUES ( '" + txtBoxID.Text.ToString() + "','" + txtBoxName.Text.ToString() + "','" + ((CheckBox)ctrl).Text.ToString() + "')", con);
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
}
}
}
该应用程序给了我这些结果:
ID Customer_Name Item_Name Item_Model Item_Color
1 Mulenga Laptop NULL NULL
如何在Item_Model和Item_Color列中添加数据?
非常感谢您的协助。
(如xxbbcc所说, 切勿串联命令文本,并始终使用参数)
为此,您可以执行以下操作(代码中的注释)
请记住,此代码假定每个组仅选中一个复选框,并且它将获得第一个选中的复选框文本。 最好使用RadioButtons
代替CheckBoxes
。
private void btnAdd_Click(object sender, EventArgs e)
{
//find all checkbox controls in group, get selected one and get its text.
string name = groupBox1.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string model = groupBox2.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
string color = groupBox3.Controls.OfType<CheckBox>().FirstOrDefault(cb => cb.Checked).Text;
//connection
SqlConnection con = new SqlConnection(conString);
//command text (WITH PARAMETERS!)
string cmdText =
@"
INSERT INTO Demo_Table
(ID,Customer_Name,Item_Name, item_model, item_color)
VALUES
(@id, @customer_name, @item_name, @item_model, @item_color)
";
SqlCommand cmd = new SqlCommand(cmdText, con);
//add params
cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = txtBoxID.Text;
cmd.Parameters.Add("@customer_name", SqlDbType.VarChar).Value = txtBoxName.Text;
cmd.Parameters.Add("@item_name", SqlDbType.VarChar).Value = name;
cmd.Parameters.Add("@item_model", SqlDbType.VarChar).Value = model;
cmd.Parameters.Add("@item_color", SqlDbType.VarChar).Value = color;
//execute query
sqlcmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data added to table");
}
如果您还有其他问题,请随时提问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.