我基本上有3个分别名为Latte,Espresso和Cappuccino的按钮,它们将提示要求确认的同一对话框。我想知道如何将不同名称的产品插入SQL Server数据库。
现在,我在@ProductName
下插入了“ Espresso”,它显示在数据库中。
表格2(我在其中单击了三个按钮)
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void bLatte_Click(object sender, EventArgs e)
{
msg m = new msg();
this.TopMost = false;
m.TopMost = true;
m.Show();
}
private void bEspresso_Click(object sender, EventArgs e)
{
msg m = new msg();
this.TopMost = false;
m.TopMost = true;
m.Show();
}
private void bCappuccino_Click(object sender, EventArgs e)
{
msg m = new msg();
this.TopMost = false;
m.TopMost = true;
m.Show();
}
}
对话框
private void bconfirm_Click(object sender, EventArgs e)
{
timer1.Start();
label1.Text = Globals.thank;
label2.Text = Globals.thank2;
bconfirm.Hide();
bcancel.Hide();
string POSconnectionStr;
POSconnectionStr = "Data Source=COMMON-PC\\SQLEXPRESS2014;Initial Catalog=cafeDb;Integrated Security = false; Connect Timeout = 10; Encrypt = False; TrustServerCertificate = False; " +
"ApplicationIntent = ReadWrite; MultiSubnetFailover = False;" ;
using (SqlConnection con = new SqlConnection(POSconnectionStr))
{
// create SQL connection object. Be sure to put a valid connection string
// SqlConnection Con = new SqlConnection("MyConnectionString");
// create command object with SQL query and link to connection object
SqlCommand Cmd = new SqlCommand("INSERT INTO tblOrder" +
"(ProductName, CreatedAt, Status) " +
"VALUES(@ProductName, @CreatedAt, @Status)", con);
// create your parameters
Cmd.Parameters.Add("@ProductName", System.Data.SqlDbType.VarChar);
Cmd.Parameters.Add("@CreatedAt", System.Data.SqlDbType.DateTime);
Cmd.Parameters.Add("@Status", System.Data.SqlDbType.VarChar);
// set values to parameters from textboxes
Cmd.Parameters["@ProductName"].Value = "Espresso";
Cmd.Parameters["@CreatedAt"].Value = DateTime.Now;
Cmd.Parameters["@Status"].Value = "Initiated";
// open sql connection
con.Open();
// execute the query and return number of rows affected, should be one
int RowsAffected = Cmd.ExecuteNonQuery();
// close connection when done
con.Close();
}
}
答案 0 :(得分:0)
首先,所有按钮单击事件都执行相同的行为,因此实际上您只需要单击事件,就可以在属性事件选项卡上分配所有按钮来触发它。
第二,在Winform中,控件具有Tag
属性,该属性可以携带您分配的数据。
在点击事件中,您可以通过将Tag
转换回sender
来检索Button
。喜欢
private void button_Click(object sender, EventArgs e)
{
label1.Text = ((Button)sender).Tag.ToString();
}
最后,棘手的部分。 new msg()
似乎是一个包含bconfirm
的对话框。
因此,您需要找到一些方法来收集在Form2
中收集的标签。例如,修改类构造函数以携带它。
// in form2
private void button_Click(object sender, EventArgs e)
{
var tag = ((Button)sender).Tag.ToString();
msg m = new msg(tag);
this.TopMost = false;
m.TopMost = true;
m.Show();
}
// in dialog
class msg
{
private string _tag = "";
public msg(string tag)
{
_tag = tag;
}
private void bconfirm_Click(object sender, EventArgs e)
{
...
using (SqlConnection con = new SqlConnection(POSconnectionStr))
{
...
Cmd.Parameters["@ProductName"].Value = _tag;
...
}
}
}