我有一个查询从文本框搜索数据库。 我的问题是如何逐列将搜索结果插入到分隔的文本框中,我的意思是每列都转到一个文本框。
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:1)
试试这个:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(@"Select Name, FileName From Table Where Name Like @Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("@Name", string.Format("%{0}%", textBox1.Text));
}
答案 1 :(得分:0)
我认为,您的搜索只返回一行。 您可以使用datareader来实现这一目标。我用下面的代码修改了你的函数:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
注意:您的代码容易受到sqlinjection的攻击。学习避免它的事情。