using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace STS { public partial class Form2 : Form { private SqlConnection conn2; public event EventHandler Form2Closed; public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { conn2 = new SqlConnection(); conn2.ConnectionString = "Server=localhost;Database=TaskManagementDB;Trusted_Connection=True;"; defaultValue_Set(); } //设置默认值 private void defaultValue_Set() { taskType_tb.Text = "调度任务"; jobType_cbb.SelectedIndex = 0; RTI_tb.Text = "-1"; taskStatus_tb.Text = "开始执行"; startLocation_tb.Text = "-"; endLocation_tb.Text = "-"; } //判断字符串后5位是否为数字 private bool isDigit(string str) { if (str.Length != 6) { return false; } for (int i = 1; i < str.Length; i++) { if (str[i] < '0' || str[i] > '9') { return false; } } return true; } private void button1_Click(object sender, EventArgs e) { //判断条码格式是否正确 if (barcode_tb.Text.Equals("")) { MessageBox.Show("条码不能为空!"); return; } if (barcode_tb.Text[0].ToString() != "T" || !isDigit(barcode_tb.Text.ToString())) { MessageBox.Show("条码格式错误!\n应以T开头后面跟5个数字"); return; } conn2.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn2; //判断数据库中是否已经有该条码 cmd.CommandText = $"select * from STM where Barcode='{barcode_tb.Text}'"; cmd.ExecuteNonQuery(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { MessageBox.Show("该条码已存在!"); return; } reader.Close(); //没有则插入数据 cmd.CommandText = $"insert into STM values('{barcode_tb.Text}','{STI_tb.Text}','{RTI_tb.Text}','{taskType_tb.Text}'," + $"'{jobType_cbb.Text}','{startPoint_tb.Text}','{startLocation_tb.Text}','{endPoint_tb.Text}'," + $"'{endLocation_tb.Text}','{taskStatus_tb.Text}','{startTime_dtp.Value.ToString("yyyy-MM-dd HH:mm:ss")}','{errorInfor_tb.Text}')"; Console.WriteLine(cmd.CommandText); int count = cmd.ExecuteNonQuery(); if (count > 0) { MessageBox.Show("提交成功!"); //关闭该窗口 this.Close(); } else { MessageBox.Show("提交失败!"); } conn2.Close(); } //关闭窗口时触发事件 private void Form2_FormClosed(object sender, FormClosedEventArgs e) { Form2Closed?.Invoke(this, EventArgs.Empty); } //获得焦点 private void barcode_tb_GotFocus(object sender, EventArgs e) { //点击时如果文本框里是默认值才执行以下代码 if (barcode_tb.Text.Equals("T*****")) { barcode_tb.Text = ""; barcode_tb.ForeColor = Color.Black; } } //失去焦点 private void barcode_tb_LostFocus(object sender, EventArgs e) { if (barcode_tb.Text.Equals("")) { barcode_tb.Text = "T*****"; barcode_tb.ForeColor = Color.Gray; } } } }