【问题标题】:Filtering the list C# ms access过滤列表 C# ms 访问
【发布时间】:2011-10-12 18:49:40
【问题描述】:

我的计划是当我插入字母 M 时,单词开头的整个字母 M 将使用列表框显示,但我不能这样做。我使用了这段代码,但我找不到它为什么不起作用:

conn.Open();
OleDbCommand cmd2 = new OleDbCommand("SELECT fnID, Lastname, Firstname, Middlename FROM tbl_Fullname WHERE Firstname LIKE '%?'", conn);
cmd2.Parameters.Add("@Firstname", OleDbType.VarChar).Value = textBox3.Text;
try
{
  OleDbDataReader dr = cmd2.ExecuteReader();
  if (dr.Read())
  {
    textBox1.Text = dr[0].ToString();   //fnID
    listBox1.Items.Add(dr[1].ToString()); //Lastname 
    textBox3.Text = dr[2].ToString();   //Firstname
    textBox4.Text = dr[3].ToString();   //Middlename
  }
  else
  {
    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    textBox4.Text = "";
    //MessageBox.Show("No result");
  }
}
catch (Exception ex)
{
  MessageBox.Show(ex.Message);
}
conn.Close();

【问题讨论】:

  • 您能否重新表述您的计划声明(您的第一行),以便我们易于阅读(并且有些意义)?

标签: c# filtering


【解决方案1】:

您的查询错误:

LIKE '%?'

首先 % 是通配符,所以它需要在参数之后

其次,我不确定这是否会起作用-实际上我很确定它不会,即您不能将参数放入带引号的字符串中-所以我认为您需要以下内容查询

LIKE ?

参数设置类似于:

.Value = textBox3.Text + "%"

【讨论】:

    【解决方案2】:

    这是我的新过滤代码:

    conn.Open();
                OleDbCommand cmd2 = new OleDbCommand("SELECT fnID,Lastname,Firstname,Middlename FROM tbl_Fullname WHERE Firstname LIKE '" + textBox3.Text + "%'", conn);
    
                try
                {
                    OleDbDataReader dr = cmd2.ExecuteReader();
    
                    while (dr.Read())
                    {
                        textBox1.Text = dr[0].ToString();   //fnID
                        textBox2.Text = dr[1].ToString();
                        listBox1.Items.Add(dr[1].ToString()); //Lastname
                        textBox3.Text = dr[2].ToString();   //Firstname
                        textBox4.Text = dr[3].ToString();   //Middlename
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                conn.Close();
    

    效果很好。不知道有没有bug。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多