如何使用WPF在数据网格中显示SQL搜索结果

时间:2014-07-09 09:22:11

标签: c# sql wpf datagrid

private void Button_Click(object sender, RoutedEventArgs e)
    {
        SqlConnection sc = new SqlConnection();
        SqlCommand com = new SqlCommand();

        sc.Open();
        com.Connection = sc;
        string sql;
        {
             sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
            {
                grdSearch.ItemsSource = sql;
                sc.Close();
            }

这是我的代码,当我按下搜索按钮时没有显示任何内容...有人可以帮助我解决这个问题,我没有收到任何错误

2 个答案:

答案 0 :(得分:0)

使用此

 using (SqlConnection con = new SqlConnection(ConString))

    {

        CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
        SqlCommand cmd = new SqlCommand(CmdString, con);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable("Employee");

        sda.Fill(dt);

        grdSearch.ItemsSource = dt.DefaultView;

    }

答案 1 :(得分:0)

<强>问题

SQL查询不正确:

  1. 应该像SELECT * FROM TABLENAME
  2. 在WHERE子句[Forename] == 'txtSearch.Text'中,== =和文本框值应使用+进行连接。
  3. 固定代码:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
    
         string sConn = @"Data Source=MYDS;Initial Catalog=MyCat;
                     User ID=MyUser;Password=MyPass;";
    
    
        using(SqlConnection sc = new SqlConnection(sConn))
        {
            sc.Open();
            string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= @Forename";
            SqlCommand com = new SqlCommand(sql, sc);       
            com.Parameters.AddWithValue("@Forename", txtSearch.Text);
    
            using(SqlDataAdapter adapter = new SqlDataAdapter(com))
            {
               DataTable dt = new DataTable();
               adapter.Fill(dt);
               grdSearch.ItemsSource = dt.DefaultView;              
            }
        }
    }