System.Data.EvaluateException: 'Cannot find column [NameID].'

System.Data.EvaluateException: 'Cannot find column [NameID].'

我想使用搜索文本框来过滤 Visual Studio 中的 datagridview,您将在其中输入某个主键(即 NameID)以过滤 datagridview 中的结果。它抛出标题中指出的错误。

我已尝试将代码从 NameID 更改为 [NameID],但此操作无效。

    private void TxtNamecSearch_TextChanged(object sender, EventArgs e)
    {
        DataView dtvNames = new DataView(dtNames);
        dtvNames.RowFilter = string.Format("Convert    
    (NameID,'System.String') Like '%{0}%'", TxtNameSearch.Text);     //   
    Errror occurs on this line
        NameDataGridView.DataSource = dtvNames;
    }

我希望在文本框中键入,主键 [NameID] 是一个数字,datagridview 中的结果将自动按列 "NameID"

过滤

我没有将名为 NameID 的 DataColumn 添加到我的数据表中,因为此列名称 "NameID" 是从 MySQL 数据库中检索的,并且已填充到 Datagridview 中。 结果,我不得不更改代码,下面的代码现在可以正常工作了:-

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;


public class Form1
{
private BindingSource NameBindingSource;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
    // Create a new DataTable
    DataTable dtName = new DataTable();

    // Add the NameID column
    dtName.Columns.Add(new DataColumn("NameID"));

    // Create a new BindingSource
    NameBindingSource = new BindingSource();
    // Bind the DataTable to the BindingSource
    NameBindingSource.DataSource = dtName;

    // Bind the BindingSource to the DataGridView
    NameDataGridView.DataSource = NameBindingSource;
  }

  private void TxtNameSearch_TextChanged(System.Object sender, System.EventArgs e)
  {
        // Set the filter
        NameBindingSource.Filter = string.Format("Convert         
  (NameID, 'System.String') LIKE '%{0}%'", TxtNameSearch.Text);
  }
 }