我有从 sql 数据库中获取数据的列表视图。我想通过在文本框中输入的文本进行搜索,并在单击按钮后显示结果并隐藏不匹配的记录
这是我的方法
请帮助
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Inventory_Manager_Pro
{
public partial class Modify : Form
{
public SqlConnection cn = new SqlConnection("Data Source=10.0.0.13;Initial Catalog=INVENTDB;Persist Security Info=True;User ID=sa;Password=farespila010A@;Encrypt=False");
public Modify()
{
InitializeComponent();
}
private void populate()
{
listView1.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT * FROM lapdev", cn);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["fillingcode"].ToString());
it.SubItems.Add(dr["username"].ToString());
it.SubItems.Add(dr["branch"].ToString());
it.SubItems.Add(dr["department"].ToString());
it.SubItems.Add(dr["agency"].ToString());
it.SubItems.Add(dr["computername"].ToString());
it.SubItems.Add(dr["lapmodel"].ToString());
it.SubItems.Add(dr["lapserial"].ToString());
it.SubItems.Add(dr["assetnumber"].ToString());
it.SubItems.Add(dr["os"].ToString());
it.SubItems.Add(dr["winlicense"].ToString());
it.SubItems.Add(dr["office"].ToString());
it.SubItems.Add(dr["officelicense"].ToString());
it.SubItems.Add(dr["hddsize"].ToString());
it.SubItems.Add(dr["processor"].ToString());
it.SubItems.Add(dr["ram"].ToString());
it.SubItems.Add(dr["macadress"].ToString());
it.SubItems.Add(dr["ipadress"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Modify_Shown(object sender, EventArgs e)
{
try
{
cn.Open();
populate();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear(); // clear list items before adding
listView1.Items.AddRange(Items.Where(i=>string.IsNullOrEmpty(textBox1.Text)||i.Name.StartsWith(textBox1.Text))
.Select(c => new ListViewItem(c.Name)).ToArray());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}