You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在DataGridView中全局搜索及基于文本文件构建该控件的技术问询

Hey there! Let's break this down into two practical parts: getting your DataGridView populated from those text files, then adding the global search functionality you're after.

1. Populating DataGridView from Text Files

First, let's polish up your existing code to fully load the text file data into your DataTable (I’m assuming ls_datenTabelle is a DataTable instance) and bind it properly to the DataGridView.

Here's the updated, commented code snippet:

private void Button1_Click(object sender, EventArgs e)
{
    // Clear existing data and columns to avoid duplicates
    ls_datenTabelle.Clear();
    ls_datenTabelle.Columns.Clear();

    // Get selected customer from combo box (add safety check for null)
    string kdstr = comboBox1.SelectedItem?.ToString() ?? string.Empty;
    if (string.IsNullOrEmpty(kdstr))
    {
        MessageBox.Show("Please select a customer first!");
        return;
    }

    // Define file paths safely with Path.Combine (avoids formatting bugs)
    string fileName2 = $"{kdstr}.txt";
    string sourcePath = $@"H:\import_directoy\customer{kdstr}";
    string fullFilePath = Path.Combine(sourcePath, fileName2);

    // Check if the target file exists before reading
    if (!File.Exists(fullFilePath))
    {
        MessageBox.Show($"File not found: {fullFilePath}");
        return;
    }

    // Read all lines from the text file
    string[] lines = File.ReadAllLines(fullFilePath);
    if (lines.Length == 0)
    {
        MessageBox.Show("The selected file is empty!");
        return;
    }

    // Assume first line is column headers (adjust if your file has no headers)
    string[] headers = lines[0].Split('\t'); // Using tab as separator—swap to ',' for CSV
    foreach (string header in headers)
    {
        ls_datenTabelle.Columns.Add(header);
    }

    // Add data rows from remaining lines
    for (int i = 1; i < lines.Length; i++)
    {
        string[] rowData = lines[i].Split('\t');
        // Ensure row has matching column count to avoid errors
        if (rowData.Length == headers.Length)
        {
            ls_datenTabelle.Rows.Add(rowData);
        }
    }

    // Bind DataTable to DataGridView (we'll adjust this later for search)
    dataGridView1.DataSource = ls_datenTabelle;
}

Quick notes here:

  • Used Path.Combine instead of string concatenation to avoid path-related bugs
  • Added safety checks for missing selections, missing files, and empty files
  • Assumed tab-separated values with a header row—tweak the Split character if your file uses commas or another separator
2. Implementing Global Search for DataGridView

For a smooth, efficient search experience, using a BindingSource as an intermediary between your DataTable and DataGridView is the best approach. It makes filtering trivial while preserving sorting and selection states.

Step 1: Add a Search TextBox

Drop a TextBox (name it txtSearch) onto your form—this will be where users type their search terms.

Step 2: Set Up the BindingSource

Update your form's initialization code (like Form_Load) to wire up the BindingSource:

private BindingSource bindingSource = new BindingSource();

private void Form1_Load(object sender, EventArgs e)
{
    // Bind DataTable to BindingSource
    bindingSource.DataSource = ls_datenTabelle;
    // Bind BindingSource to DataGridView
    dataGridView1.DataSource = bindingSource;
}

(Don’t forget to update your Button1_Click code to set bindingSource.DataSource = ls_datenTabelle instead of directly setting the DataGridView’s DataSource, after populating the table.)

Step 3: Add Search Logic to TextBox’s TextChanged Event

Double-click the txtSearch box to generate the TextChanged handler, then add this code:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    string searchTerm = txtSearch.Text.Trim();
    
    if (string.IsNullOrEmpty(searchTerm))
    {
        // Show all rows when search box is empty
        bindingSource.Filter = string.Empty;
        return;
    }

    // Build filter to check every column for the search term
    StringBuilder filterBuilder = new StringBuilder();
    foreach (DataColumn column in ls_datenTabelle.Columns)
    {
        if (filterBuilder.Length > 0)
        {
            filterBuilder.Append(" OR ");
        }
        // Make search case-insensitive by converting to uppercase
        filterBuilder.Append($"{column.ColumnName} LIKE '%{searchTerm.ToUpper()}%'");
    }

    // Apply the filter to the BindingSource
    bindingSource.Filter = filterBuilder.ToString();
}

This code:

  • Restores all rows when the search box is cleared
  • Checks every column for partial matches of the search term
  • Makes the search case-insensitive (remove .ToUpper() if you want case-sensitive results)
  • Uses the BindingSource’s built-in filtering, which is far more efficient than manually looping through rows

Edge Case Tip

If your text file includes numeric or date columns, adjust the filter logic for those columns—LIKE works best with text. For example, for numeric columns, you could check if the search term is a valid number and use equality checks instead.


内容的提问来源于stack exchange,提问作者Scheennie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:01:22