开发者

C# code for Search button

开发者 https://www.devze.com 2023-01-23 02:13 出处:网络
I have a (Sql Server 2008) table called Courses with course_id,course_name and course_description as its fields

I have a (Sql Server 2008) table called Courses with course_id,course_name and course_description as its fields In the front end, I have a text box and a search button. In the text box, when I give a course name (even a part of it)..in the button click event, all the course names should show up.

How do I code this in C#? Any help would 开发者_如何学编程be appreciated..


you can select from sql table with where statement

eg, "whre course_name = 'a'"

a means it will return all course name with a character a for eg, matehmatics

can search for details about * thing in google.


First of all, you should use "LIKE" operator in sql command in order to list all the results containing the criteria. Secondly, you should use SqlDataReader given that you are only retrieving values. Thirdly, you should use a parameter in order to prevent sql injection. Since you did not specify how you want to display the results, I populate a list from the results in my sample code below. I hope this helps you and future viewers.

    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
        }
    }


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消