2015-06-28 56 views
0

我的數據庫包含員工ID,姓名,電子郵件地址和電話號碼。我已經使用員工ID選擇一個下拉列表,爲了這個,我寫了這個代碼:通過從DropDownList中選擇employee_id來獲取員工信息

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Data; 

public partial class Employeedetails : System.Web.UI.Page 
{ 
    SqlConnection con = new SqlConnection("Data Source=REVATI-PC;Initial Catalog=Test_Database;Integrated Security=True"); 
    SqlCommand cmd; 
    SqlDataAdapter da; 
    string query; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     con.Open(); 
     query = "select Employee_ID from Employee"; 
     cmd = new SqlCommand(query, con); 

     SqlDataReader dr = cmd.ExecuteReader(); 

     while (dr.Read()) 
     { 
      DropDownList1.Items.Add(dr[0].ToString()); 
     } 

     con.Close(); 

而是通過點擊這些特定的ID,我沒有得到其他信息。爲此,我使用SelectIndexchanged事件,寫一個選擇查詢

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     string query = "select Employee_ID from Employee where Employee_ID='" + DropDownList1.SelectedValue.ToString() + "'"; 
     con.Open(); 
} 

但它不工作

+0

一點也沒有」 t看起來像你曾經在DropDownList1_SelectedIndexChanged()執行您的查詢... –

+1

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29。 aspx) - 您應該不**將您的SQL語句連接在一起 - 使用**參數化查詢**來避免SQL注入 –

回答

0

試試這個

string empname=""; 
    string query = "select * from Employee where [email protected]"; 
    cmd = new SqlCommand(query, con); 
    cmd.Parameters.AddWithValue("@value1",DropDownList1.SelectedValue.ToString()); 
    con.Open(); 
    SqlDataReader dr = cmd.ExecuteReader(); 
    while (dr.Read()) 
    { 
     empname=dr["Employee_Name"].ToString(); 
    // and so on 
    } 
    con.Close(); 
0

你所看到的問題是雙重的。您在查詢期間只選擇員工編號,而不是任何附加信息,並且如果您發佈的功能已完成,您似乎不會運行查詢。要選擇更多的信息,選擇使用SELECT *(如下),或選擇具體列名和列名從閱讀器讀取出來

嘗試更新的SelectedIndexChanged函數將此:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string query = "select * from Employee where Employee_ID='" + DropDownList1.SelectedValue.ToString() + "'"; 

    conn.Open(); 

    cmd = new SqlCommand(query, con); 

    SqlDataReader dr = cmd.ExecuteReader(); 

    while (dr.Read()) 
    { 
     DropDownList1.Items.Add(dr["<column_name>"].ToString()); 
    } 

    con.Close(); 
}