由于编写一个完整的C# WinForm应用程序超出了这个文本平台的限制,我将为您提供一个基本的框架和关键代码段。您需要根据您的数据库类型(如SQL Server、MySQL等)以及具体的表结构来调整数据库连接字符串和查询语句。 首先,确保在项目中添加了对System.Data.SqlClient(对于SQL Server)或MySql.Data(对于MySQL)等数据访问库的引用。 ```csharp using System; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; // 如果是SQL Server,如果是MySQL,则使用 using MySql.Data.MySqlClient; public partial class MainForm : Form { private string connectionString = "Data Source=yourServerAddress;Initial Catalog=barcode;User ID=yourUsername;Password=yourPassword;"; // 请替换为实际的数据库连接字符串 public MainForm() { InitializeComponent(); // 假设你有三个TextBox分别用来输入三个条形码 textBox1.TextChanged += OnBarcodeTextChanged; textBox2.TextChanged += OnBarcodeTextChanged; textBox3.TextChanged += OnBarcodeTextChanged; } private void OnBarcodeTextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text) && !string.IsNullOrEmpty(textBox3.Text)) { // 查询数据库 string query = $"SELECT * FROM mo WHERE Barcode1 = '{textBox1.Text}' OR Barcode2 = '{textBox2.Text}' OR Barcode3 = '{textBox3.Text}'"; ExecuteQuery(query); } } private void ExecuteQuery(string sql) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(sql, connection); try { connection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // 在这里处理查询结果,例如显示在DataGridView或者任何其他UI元素中 dataGridView1.DataSource = dataTable; } catch (Exception ex) { MessageBox.Show($"查询时发生错误: {ex.Message}"); } finally { connection.Close(); } } } } ``` 上述代码仅作为示例,并未包含图形化设置连接参数部分。通常,您可以创建一个设置窗体,用户可以在其中输入服务器地址、用户名、密码等信息,然后保存到配置文件或数据库中。在程序启动时读取这些设置并初始化连接字符串。 为了防止SQL注入攻击,应尽量避免直接拼接SQL语句,而是采用参数化查询的方式进行操作。对于上述代码中的查询部分,应当改为: ```csharp private void OnBarcodeTextChanged(object sender, EventArgs e) { string query = "SELECT * FROM mo WHERE Barcode1 = @Barcode1 OR Barcode2 = @Barcode2 OR Barcode3 = @Barcode3"; ExecuteQueryWithParameters(query, textBox1.Text, textBox2.Text, textBox3.Text); } private void ExecuteQueryWithParameters(string sql, string barcode1, string barcode2, string barcode3) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@Barcode1", barcode1); command.Parameters.AddWithValue("@Barcode2", barcode2); command.Parameters.AddWithValue("@Barcode3", barcode3); try { connection.Open(); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); dataGridView1.DataSource = dataTable; } catch (Exception ex) { MessageBox.Show($"查询时发生错误: {ex.Message}"); } finally { connection.Close(); } } } ``` [2024-01-14 08:44:10 | AI写代码神器 | 775点数解答]