c# - 使用 DataGridView 在 C# 中键入时进行搜索
问题描述
我只是想和大家分享一些知识,因为我花了将近半天的时间在VS2017中使用winforms搜索“键入时搜索”的解决方案。我发现的大多数其他解决方案都使用 SQL 数据库作为数据源,或者建议使用其他工具或控件,这不是我正在寻找的解决方案。
无论如何,我向 Web API 发出请求并将响应放入列表中。然后,我将该列表用作 DataGridView 控件的数据源。然后我使用 Key_Up 作为触发器。以下是我的最终解决方案,效果很好!
希望这可以帮助!
解决方案
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AddUser_API
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
/*Makes the request to API for the groups when the form loads. I obviously have a different class that handles this request*/
Request userClient = new Request();
//endpoint is a GET request
userClient.endPoint = userClient.endPoint;
userClient.httpMethod = httpVerb.GET;
string strResponse = string.Empty;
strResponse = userClient.makeRequest();
/*This will put the response into a list then fill the datagridview control with the Web API response*/
List<getUser> grpName = JsonConvert.DeserializeObject<List<getUser>>(strResponse);
dgvUserList.DataSource = grpName;
//Cosmetics
dgvUserList.Columns[0].DefaultCellStyle.Padding = new Padding(0, 0, 28, 0);
dgvUserList.Columns[1].DefaultCellStyle.Padding = new Padding(0, 0, 28, 0);
}
/* the following key up will allow the user to search as they type in the textbox control*/
private void txtbxByUsername_KeyUp(object sender, KeyEventArgs e)
{
string searchValue = txtbxByUsername.Text.ToLower();
dgvUserList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvUserList.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().ToLower().Contains(searchValue))
{
int rowIndex = row.Index;
dgvUserList.Rows[rowIndex].Selected = true;
break;
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
}
}
推荐阅读
- node.js - firebase 云函数从批处理函数返回 json 对象
- flutter - 如何将上下文注入自定义函数?
- c# - gmail 日历在主机上不起作用(asp.net mvc)
- java - Java: Trying to take keyboard input and evaluate it in an if/else condition to set a boolean value to true or false
- html - 为什么我的字体大小在我的 h1、h2、p 中不起作用
- qlabel - Pyqt5 如何在 QtabWidget 中的 Qlabel 中设置文本
- windows - 我可以像在 Windows 中一样在 linux 中创建过滤器驱动程序吗?
- sharepoint - 如果我正确处理 SPSite 和 SPweb,我不是
- php - 网站用户如何删除输入值?
- kubernetes - OpenShift 角色创建配额