WinForm------给GridControl添加搜索功能
//按钮点击事件
private void Btn_Search_Click(object sender, EventArgs e) { //获取编辑框的值 string text = this.textEdit1.Text; ColumnView view = (ColumnView)UserManagementGrid.FocusedView; GridColumn column = null; //判断是否为空 if (!text.Equals("")) { //判断首个字符是否是英文 if ((text[0] > 'a' && text[0] < 'z') || (text[0] > 'A' && text[0] < 'Z')) { //英文(UserName为数据库里面的列名,TrueName同理) column = view.Columns["UserName"]; } else { //不是英文 column = view.Columns["TrueName"]; } } else { ShowInfo("请输入用户名或姓名!"); } if (column != null) { int rhFound = 0; //从第0行开始查询,查询的列,匹配列中的值 rhFound = view.LocateByDisplayText(0, column, text); //如果行值正常,即条件满足,存在 if (rhFound != DevExpress.XtraGrid.GridControl.InvalidRowHandle) { view.FocusedRowHandle = rhFound; view.FocusedColumn = column; view.SelectRow(rhFound); } else { ShowInfo("无此用户名或姓名!"); } } } /// <summary> /// 行风格设置 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UserManagementView_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e) { //如果行不是焦点行,则背景色为白色 if (e.RowHandle != UserManagementView.FocusedRowHandle) { e.Appearance.BackColor = Color.White; } }
方法二:
通过特定列的值搜索
public List<Users> GetUsersByShowText(string text) { return _db.Users.Where(p => p.UName.Contains(text) || p.TrueName.Contains(text)).ToList(); }