如何使用ms访问数据库在c#中使用Like运算符?

时间:2016-10-20 13:35:13

标签: c#

我正在为我们的项目制作一个Windows窗体应用程序,我的项目是关于调度系统,我试图从包含Day和Instructor的ms访问数据库中搜索数据。 Day列只有两个值" MWF和TTH"。当我搜索MWF时,我希望包含MWF的所有数据显示在我的列表视图中,但只显示一个数据。我该如何解决这个问题?

CODE HERE

public void Search()
    {
        c.OpenDb();
        c.com.CommandType = CommandType.Text;
        c.com.CommandText = "SELECT * FROM ScheduleInfo WHERE Day LIKE '%" + comboBox1.Text + "%' AND Instructor LIKE '%" + textBox9.Text + "%' ";
        c.com.Connection = c.con;
        c.dr = c.com.ExecuteReader();
        if (c.dr.Read())
        {
            ListViewItem fp = new ListViewItem(c.dr["Day"].ToString());
            fp.SubItems.Add(c.dr["Time"].ToString());
            fp.SubItems.Add(c.dr["Instructor"].ToString());
            fp.SubItems.Add(c.dr["Subject"].ToString());
            fp.SubItems.Add(c.dr["Room"].ToString());
            listView5.Items.Add(fp);

        }
        else
        {
            Notfound nf = new Notfound();
            nf.ShowDialog();
            if (nf.DialogResult == DialogResult.OK)
            {
                textBox9.Clear();
            }
        }
        c.CloseDb();
    }

    private void button13_Click(object sender, EventArgs e)
    {
        Search();
    }

2 个答案:

答案 0 :(得分:2)

if (c.dr.Read())更改为while (c.dr.Read())

    bool hasRecords = false;

    while (c.dr.Read()) {
      ListViewItem fp = new ListViewItem(c.dr["Day"].ToString());

      fp.SubItems.Add(c.dr["Time"].ToString());
      fp.SubItems.Add(c.dr["Instructor"].ToString());
      fp.SubItems.Add(c.dr["Subject"].ToString());
      fp.SubItems.Add(c.dr["Room"].ToString());
      listView5.Items.Add(fp);

      hasRecords = true;
   }

   if (!hasRecords) {
     Notfound nf = new Notfound();

     nf.ShowDialog();

     if (nf.DialogResult == DialogResult.OK)
        textBox9.Clear();
   }

答案 1 :(得分:0)

Access使用*字符作为通配符,而不是%字符。

http://www.techrepublic.com/article/10-tips-for-using-wildcard-characters-in-microsoft-access-criteria-expressions/

SQL Server使用%字符作为通配符。也许那就是你在想什么。