C# MySQL 搜索表格并展示结果到 DataGridView
以下是一个示例代码,演示如何使用 C# 和 MySQL 来搜索表中包含搜索词的所有行,并在 dataGridView 中展示出来。
首先,确保已经安装了 MySQL Connector/NET,可以在 Visual Studio 的 NuGet 包管理器中搜索并安装。
然后,创建一个 Windows 窗体应用程序,并在窗体上添加一个 dataGridView 和一个搜索按钮。
接下来,将以下代码添加到窗体的代码文件中:
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
namespace SearchMySQL
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Form1()
{
InitializeComponent();
server = 'localhost'; // MySQL服务器地址
database = 'your_database'; // 数据库名称
uid = 'your_username'; // 用户名
password = 'your_password'; // 密码
}
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = $'SERVER={server};DATABASE={database};UID={uid};PASSWORD={password};';
connection = new MySqlConnection(connectionString);
}
private void SearchButton_Click(object sender, EventArgs e)
{
string searchWord = SearchTextBox.Text;
try
{
connection.Open();
string query = $'SELECT * FROM your_table WHERE column1 LIKE '%{searchWord}%' OR column2 LIKE '%{searchWord}%';';
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridView.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show('Error: ' + ex.Message);
}
finally
{
connection.Close();
}
}
}
}
请注意,上面的代码中,你需要将your_database替换为你要搜索的数据库名称,your_username替换为你的 MySQL 用户名,your_password替换为你的 MySQL 密码,your_table替换为你要搜索的表名,column1和column2替换为你要搜索的列名。
然后,将搜索按钮的 Click 事件与SearchButton_Click方法关联,并将 dataGridView 的数据源设置为dataTable。
现在你可以运行应用程序,输入搜索词并点击搜索按钮,dataGridView 将会显示出包含搜索词的所有行。
原文地址: https://www.cveoy.top/t/topic/lJkw 著作权归作者所有。请勿转载和采集!