我有一個名爲Courses with course_id,course_name和course_description作爲其字段的(Sql Server 2008)表 在前端,我有一個文本框和一個搜索按鈕。在文本框中,當我給出一個課程名稱(甚至是它的一部分)..在按鈕點擊事件中,所有課程名稱都應該顯示出來。搜索按鈕的C#代碼
如何在C#中編寫此代碼?任何幫助,將不勝感激..
我有一個名爲Courses with course_id,course_name和course_description作爲其字段的(Sql Server 2008)表 在前端,我有一個文本框和一個搜索按鈕。在文本框中,當我給出一個課程名稱(甚至是它的一部分)..在按鈕點擊事件中,所有課程名稱都應該顯示出來。搜索按鈕的C#代碼
如何在C#中編寫此代碼?任何幫助,將不勝感激..
可以從SQL表選擇where語句
例如,「whre課程名稱=‘一個’」
一個意味着將返回所有課程名稱與一個字符 例如,matehmatics
可以搜索有關*在谷歌的東西的細節。所有的
我想要寫例如, 「whre課程名稱='* A *」 但爲什麼*的東西從不包括? – william 2010-11-01 02:44:30
protected void Button1_Click1(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("select Processor,HDD,RAM,Display,Graphics,OS,processor,hdd,ram,display,os,opticaldrive,warranty,price,other,graphics,images,Warranty,Price,Images,other from System where CompanyName='"+companyname.Text+"'",con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
processor.Text = dr.GetValue(3).ToString();
}
con.Close();
}
真的不是一個好的解決方案!其實這很糟糕,制定了所有的規則。 – walther 2012-04-14 12:17:22
這是你不應該做的所有事情的教科書範例。 – 2012-04-14 23:31:48
首先,你應該使用SQL命令「LIKE」操作,以列出包含標準的所有結果。 其次,你應該使用SqlDataReader,因爲你只是檢索值。 第三,你應該使用一個參數來防止sql注入。 由於您沒有指定如何顯示結果,因此我在下面的示例代碼中填充了結果列表。我希望這可以幫助你和未來的觀衆。
private void button1_Click(object sender, EventArgs e)
{
List<string> Courses = new List<string>();
SqlConnection con = new SqlConnection("the connection string here");
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT courseName, courseDescription FROM db.Courses WHERE CourseName LIKE %@CourseName%";
cmd.Parameters.AddWithValue("@CourseName", textBox1.Text);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
string course = reader["CourseName"].ToString();
course += ", " + reader["CourseDescription"].ToString();
Courses.Add(course);
}
reader.Close();
foreach (string course in Courses)
{
//wherever and however you would like to display
}
}
http://blogs.msdn.com/b/oldnewthing/archive/2010/04/22/10000406.aspx – 2010-11-01 02:05:00