如何使用 WPF 在数据网格中显示 SQL 搜索结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24649840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:06:43 来源:igfitidea点击:
How to display SQL search results in a datagrid using WPF
提问by BenNixon
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();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
这是我拥有的代码,当我按下搜索按钮时什么也没有显示......有人可以帮我解决这个问题吗,我没有收到任何错误
采纳答案by Hassan
Problems:
问题:
SQL query is not right:
SQL 查询不对:
- It should be like
SELECT * FROM TABLENAME. - In WHERE clause
[Forename] == 'txtSearch.Text',==should=and Textbox value should be concatenated using+.
- 它应该像
SELECT * FROM TABLENAME。 - 在 WHERE 子句中
[Forename] == 'txtSearch.Text',==should=和 Textbox 值应该使用+.
Fixed Code:
固定代码:
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;
}
}
}
回答by CHash_Mike
Use this
用这个
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;
}

