我有一个显示给定目录中所有文件的应用程序。现在我想在应用程序中实现搜索功能。我使用textBox_textChanged方法来实现搜索,因为它更快。但不知怎的,我无法让它发挥作用。我不知道是什么问题。这是我的代码:
{
public partial class Form1 : Form
{ private Timer timer;
private int count;
DataTable dt = new DataTable();
DataRow dr;
String[] s1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
count = 0;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer1_Tick);
timer.Start();
s1 = Directory.GetFiles(@"C:\Documents and Settings\Administrator\Desktop\FILE","*.*",SearchOption.AllDirectories);
for (int i = 0; i <= s1.Length - 1; i++)
{
if (i == 0)
{
dt.Columns.Add("File_Name");
dt.Columns.Add("File_Type");
dt.Columns.Add("File_Size");
dt.Columns.Add("Create_Date");
}
//Get each file information
FileInfo info = new FileInfo(s1[i]);
FileSystemInfo sysInfo = new FileInfo(s1[i]);
dr = dt.NewRow();
//Get File name of each file name
dr["File_Name"] = sysInfo.Name;
//Get File Type/Extension of each file
dr["File_Type"] = sysInfo.Extension;
//Get File Size of each file in KB format
dr["File_Size"] = (info.Length / 1024).ToString();
//Get file Create Date and Time
dr["Create_Date"] = sysInfo.CreationTime.Date.ToString("dd/MM/yyyy");
//Insert collected file details in Datatable
dt.Rows.Add(dr);
//
if ((info.Length / 1024) > 5000)
{
MessageBox.Show("" + sysInfo.Name + " had reach its size limit.");
}
}
if (dt.Rows.Count > 0)
{
//Finally Add DataTable into DataGridView
dataGridView1.DataSource = dt;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count++;
if (count == 300)
{
count = 0;
timer.Stop();
Application.Restart();
}
}
public string secondsToTime(int seconds)
{
int minutes = 0;
int hours = 0;
while (seconds >= 60)
{
minutes += 1;
seconds -= 60;
}
while (minutes >= 60)
{
hours += 1;
minutes -= 60;
}
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
string strSeconds = seconds.ToString();
if (strHours.Length < 2)
strHours = "0" + strHours;
if (strMinutes.Length < 2)
strMinutes = "0" + strMinutes;
if (strSeconds.Length < 2)
strSeconds = "0" + strSeconds;
return strHours + ":" + strMinutes + ":" + strSeconds;
}
//this is the filter code fragment.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataRow[] select = dt.Select("File_Name = '" + textBox1.Text+"'");
}
}
}
答案 0 :(得分:1)
如果您正在使用TextChanged,我假设您希望匹配部分搜索,其中您键入的内容将与您输入所包含的任何文件名匹配。例如,如果您键入“He”,它将匹配“Help”,“ HelloWorld“等等。
修改强>
您应该使用BindingSource而不是直接绑定到数据表,因为它会为您提供过滤功能。
public BindingSource bindingSource;
然后,更改此代码:
if (dt.Rows.Count > 0)
{
//Finally Add DataTable into DataGridView
dataGridView1.DataSource = dt;
}
对此:
if (dt.Rows.Count > 0)
{
//Finally Add DataTable into DataGridView
bindingSource = new BindingSource();
bindingSource.DataSource = dt;
dataGridView1.DataSource = bindingSource;
}
最后将TextChanged事件处理程序更改为此以进行实际过滤:
private void textBox1_TextChanged(object sender, EventArgs e)
{
bindingSource.Filter = string.Format("File_Name LIKE '%{0}%'", textBox1.Text);
}