【问题标题】:Retrieving data in DataGridView by matching TextBox content通过匹配 TextBox 内容在 DataGridView 中检索数据
【发布时间】:2011-08-10 13:55:30
【问题描述】:

我在数据库中有 3 个表:

  1. Emp(姓名,手机号码,付款,入职日期)
  2. Addmoney(name,date_of money_taken,Type)
  3. AddDate(name,Leaving_Date)

我只想显示这 3 个表中的这些列(名称、付款、Date_of_money_Taken、Joining_date、Leaving_date),当用户在 TextBox 中输入存储在 Emp 表中的任何名称时,我在下面的代码中遇到问题。它正在抛出这个:

Exception({"The multi-part identifier \"name.Text\" could not be bound."})

private void ShowEmp_Load(object sender, EventArgs e)
{
    // create the connection string
    connectionString = GetConnectionString();
    connection = new SqlConnection(connectionString);
    queryString = "select Emp.name,Emp.Payment,Emp.JoiningDate,Addm.Date,AddDate.LeavingDate from Emp,Addm,AddDate where name.Text='" + name + " ' ";// Select * From Emp

    // create an SqlDataAdapter to execute the query
    dAdapter = new SqlDataAdapter(queryString, connection);

    // create a command builder
    cBuilder = new SqlCommandBuilder(dAdapter);

    // create a datatable to hold query results
    dTable = new DataTable();

    // fill DataTable
    dAdapter.Fill(dTable);<-EXCEPTION({"The multi-part identifier \"name.Text\" could not be bound."})

    // the DataGridView
    //DataGridView dataGridView1 = new DataGridView();

    // BindingSource to sync DataTable and DataGridView
    bSource = new BindingSource();

    // set the BindingSource DataSource
    bSource.DataSource = dTable;

    // set the DataGridView DataSource
    dataGridView1.DataSource = bSource;

}

【问题讨论】:

  • 我注意到这个方法都在'Load'事件处理程序中,所以它只会在加载时被调用一次,这是想要的效果还是你希望在按钮单击或类似的东西?

标签: c# sql datagridview


【解决方案1】:

你的查询是不是错了?试试这个查询:

queryString = "
    select 
        Emp.name, Emp.Payment, Emp.JoiningDate, Addm.Date, AddDate.LeavingDate
    from
        Emp, Addm, AddDate where Emp.name = '" + name + "' ";

当字段名称看起来应该是 Emp.name 时,您正在引用 name.Text

请注意,您真的需要使用参数来执行此操作。这对于 SQL 注入是敞开的......

【讨论】:

  • 但是在使用这个查询字符串之后,我如何在 datagridview 中显示数据,因为现在它没有在 datagridview 中显示任何内容
  • @Anonynus 您需要弄清楚这一点,因为您连接结果的方式可能存在问题。即使没有过滤,您能否让网格显示任何内容?您确定名称中的文本完全匹配吗?也许您需要 LIKE 而不是 = 签入您的 SQL。有很多事情可能是错误的。做一些诊断并重新发布。
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2020-09-01
  • 2017-08-06
相关资源
最近更新 更多