C#!怎么在DataGridView中进行查询
发布网友
发布时间:2023-08-23 05:01
我来回答
共3个回答
热心网友
时间:2024-12-11 16:24
针对DataGridView中已进行过数据绑定,即已向DataGridView中添加了一些数据,可以结合Linq查询,并让匹配查询的行高亮显示,具体实现如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Maxes_PC_Client {
public partial class frmWelcome : Form {
private int beforeMatchedRowIndex = 0;
public frmWelcome()
{
InitializeComponent();
}
private void frmWelcome_Load(object sender, EventArgs e) {
this.dataGridViewInit();
}
/// <summary>
/// DataGridView添加数据、初始化
/// </summary>
private void dataGridViewInit() {
Dictionary<String, String> map = new Dictionary<String, String>();
map.Add("Lily", "22");
map.Add("Andy", "25");
map.Add("Peter", "24");
// 在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<T, K>泛型集合的对象
BindingSource bindingSource = new BindingSource();
// 将泛型集合对象的值赋给BindingSourc对象的数据源
bindingSource.DataSource = map;
this.dataGridView.DataSource = bindingSource;
}
private void SearchButton_Click(object sender, EventArgs e) {
if (this.KeyWord.Text.Equals("")) {
return;
}
// Linq模糊查询
IEnumerable<DataGridViewRow> enumerableList = this.dataGridView.Rows.Cast<DataGridViewRow>();
List<DataGridViewRow> list = (from item in enumerableList
where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0
select item).ToList();
// 恢复之前行的背景颜色为默认的白色背景
this.dataGridView.Rows[beforeMatchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.White;
if (list.Count > 0) {
// 查找匹配行高亮显示
int matchedRowIndex = list[0].Index;
this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;
this.beforeMatchedRowIndex = matchedRowIndex;
}
}
}
}
热心网友
时间:2024-12-11 16:24
string cmd = "select * from 表名 where 查询条件='"+Text.Text+"'";
SqlCommand sql = new SqlCommand(cmd);
sql.Connection = new Connectiong("Data Source=机器名;Initial Catalog=数据库名;Integrated Security=True");
try
{
sql.Connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet DS = new DataSet();
adapter.SelectCommand = sql;
adapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
catch (SqlException o)
{
MessageBox.Show(o.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
sql.Connection.Close();
}
热心网友
时间:2024-12-11 16:25
你这个问题有点没说清楚
DataGridView的数据如果来自数据库的话
你直接去数据库查询然后用DataGridView显示查询结果就好了
不用去DataGridView中查询吧