简体   繁体   中英

About C# in ASP.NET and SQL Server

I have a drop down list that binding data from database table and I can show it, but when I wanna show the data when I selected the drop down list value, it can't show anything

Here is my code

protected void Page_Load(object sender, EventArgs e)
{ 
    if (!IsPostBack)
    {
        DropDownList1.DataSource = GetData();
        DropDownList1.DataTextField = "DEPT_NAME";
        DropDownList1.DataValueField = "DEPT_NO";
        DropDownList1.DataBind();
    }
}

protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
    string value = DropDownList1.SelectedValue;

    using (SqlConnection conn = new SqlConnection(@"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value, conn))
        {
            conn.Open();

            SqlDataReader dr = cmd.ExecuteReader();                 

            this.GridView1.Visible = true;
            GridView1.DataSource = dr;
            GridView1.DataBind();

            dr.Close();
            conn.Close();
        }               
    }
}

DataTable GetData()
{
    DataTable dt = new DataTable();

    using (SqlConnection conn = new SqlConnection(@"Data Source=server;Initial Catalog=DB;User ID=id;Password=pw"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT 'Please Select' AS DEPT_NAME , '000' AS DEPT_NO UNION SELECT DEPT_NAME , DEPT_NO FROM dept ORDER BY DEPT_NO ASC", conn))
        {
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
        }
    }

    return dt;
}
using (SqlCommand cmd = new SqlCommand("SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO = @value", conn))

cmd.Parameter.AddWithValue("@value",value);

Query ( "SELECT TEL_NO,EMP_NAME,EMP_POSITION FROM tel WHERE DEPT_NO =" +value ) will work if DEPT_NO dataType is number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM