C# 使用文本框查询数据库单据信息并展示在DataGridView中
C# 使用文本框查询数据库单据信息并展示在 DataGridView 中
本示例演示如何使用 C# 在文本框中输入单号,通过按钮查询数据库相关单据信息并展示在 DataGridView 中,同时将查询过的单号添加到 ListBox 中,点击 ListBox 中的单号可重新查询对应清单内容。
步骤
- 在窗体上添加一个文本框 (textBox1),一个按钮 (button1),一个 DataGridView (dataGridView1) 和一个 ListBox (listBox1)。
- 在窗体的代码文件中,添加以下代码:
using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Windows.Forms;namespace WindowsFormsApp{ public partial class Form1 : Form { private string connectionString = "Your_Connection_String"; // 替换成你的数据库连接字符串 public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string orderNumber = textBox1.Text; // 查询数据库获取相关单据信息 DataTable dt = GetOrderDetails(orderNumber); if (dt.Rows.Count > 0) { // 将数据绑定到 DataGridView dataGridView1.DataSource = dt; // 将单号添加到 ListBox listBox1.Items.Add(orderNumber); } else { MessageBox.Show("未找到相关单据信息!"); } } private DataTable GetOrderDetails(string orderNumber) { DataTable dt = new DataTable(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 构造查询语句 string query = "SELECT * FROM Orders WHERE OrderNumber = @OrderNumber"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@OrderNumber", orderNumber); SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(dt); } } return dt; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { string selectedOrderNumber = listBox1.SelectedItem.ToString(); // 重新查询并绑定数据 DataTable dt = GetOrderDetails(selectedOrderNumber); dataGridView1.DataSource = dt; } }} - 将 "Your_Connection_String" 替换成你的数据库连接字符串。
功能
当用户在文本框中输入单号并点击按钮时,将会查询数据库并将查询结果展示在 DataGridView 中。同时,该单号也会添加到 ListBox 中。当用户点击 ListBox 中的单号时,会重新查询该单号的清单并更新 DataGridView 中的数据。
原文地址: http://www.cveoy.top/t/topic/p4uH 著作权归作者所有。请勿转载和采集!