2017-04-07 116 views
1

這裏是我的代碼,但是當我用real ID 它運作良好替代dropdownlist.selectedvalue,所以當我從下拉列表中選擇另一個ID,我需要這樣的變化:根據下拉列表選擇從以文本檢索數據

protected void Page_Load(object sender, EventArgs e) 
{ 

    SqlCommand com = new SqlCommand("select * from UsersTable where UserName='" + DropDownListUsers.SelectedValue + "'", conn); 
    try 
    { 
     conn.Open(); 

     using (SqlDataReader red = com.ExecuteReader()) 
     { 
      while (red.Read()) 
      { 
       TextBoxpass.Text = (red["password"].ToString()); 
       TextBoxFname.Text = (red["Fname"].ToString()); 
       TextBoxLname.Text = (red["Lname"].ToString()); 
       TextBoxAddress.Text = (red["Address"].ToString()); 
       TextBoxPhone.Text = (red["PhoneNo"].ToString()); 
       TextBoxEmail.Text = (red["Email"].ToString()); 
       TextBoxpass.Text = (red["password"].ToString()); 
      } 
     } 
    } 

    finally 
    { 
     conn.Close(); 
    } 
} 

回答

0

只需添加的ToString();

DropDownListUsers.SelectedValue.ToString(); 

,並確保類似@Hung說,如果你想要把它在頁面加載時要放在

DropDownListUsers.SelectedIndex = 0; 

以上

+0

感謝,它運作良好的代碼之前的所有值< 3 –

0

爲了讓你的代碼更好,你需要在這裏做幾件事。

您需要將上面的代碼綁定到changed事件您 DropDownListUsers沒有頁面加載,或者如果你想要把它在頁面加載,你需要指定下拉列表中選擇默認值。

//server side code 
protected void DropDownListUsers_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    //code here 
} 
//Your markup 
OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged" AutoPostBack="True" 

使用參數化查詢https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx

相關問題