How do I filter my datagirdview using a textbox?

后端 未结 1 898
别跟我提以往
别跟我提以往 2021-01-29 07:23
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Te         


        
1条回答
  •  醉梦人生
    2021-01-29 08:05

    If you want to be able to filter and sort, then you can use the SortableList as above.

    If you really just want to filter, though, it's as simple as this: store the tanks list, and assign the datasource as a subset of tanks when the filter changes:

    // 'tanks' is stored as a field when loaded from disk
    private List tanks;
    
    protected void LoadData()
    {
        tanks = new List();
        string[] lines = File.ReadAllLines(@"C:\Users\bluehalo\Documents\tank chart 2.txt");
                
        for (int i = 0; i < lines.Length; i++)
        {
            TankClass tank = new TankClass(lines[i].ToString());
            tanks.Add(tank);    
        }
        
        dataGridView1.DataSource = tanks;
    }
    

    And when you want to filter:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        // name contains text
        dataGridView1.DataSource = tanks.Where(t => t.Name.IndexOf(textBox1.Text, StringComparison.OrdinalIgnoreCase) > -1).ToList()
    }  
    

    0 讨论(0)
提交回复
热议问题