2013-04-15 31 views
1

我必須將更改審計到數據庫中。在大多數頁面上,這是完美的,因爲只有文本框 - 然而,在我正在使用下拉列表的頁面上,我的代碼無法正常工作。背後如何從下拉列表中檢索文本?

<td> 
    <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDatacountry" DataTextField="country_name" DataValueField="country_id"> 
    </asp:DropDownList> 

    <asp:SqlDataSource ID="SqlDatacountry" runat="server" ConnectionString="<%$ ConnectionStrings:songtypecons %>" SelectCommand="SELECT * FROM [country_detail]"></asp:SqlDataSource> 
</td> 

代碼:

string sql1 = "selectcust_fname,cust_mname,cust_lname,cust_birthdate,cust_gender,cust_address,cust_contact_num,cust_country,cust_state,cust_city,cust_zip from cust_detail where cust_id ='" + ds.Tables["filldata"].Rows[0].ItemArray[0].ToString() + "' "; 
      SqlDataAdapter adpt1 = new SqlDataAdapter(sql1, con); 
      DataSet ds1 = new DataSet(); 
      adpt1.Fill(ds1, "custdata"); 
      if (ds1.Tables["custdata"].Rows.Count > 0) 
      { 

      for (int d = 0; d < DropDownList4.Items.Count; d++) 
      { 
       if (ds1.Tables["custdata"].Rows[0].ItemArray[7].ToString() == DropDownList4.Items[d].Text) 
       { 
        DropDownList4.Items[d].Selected = true; 
        break; 
       } 
      } 
     } 
+0

難道你不能只使用DropDownList4.SelectedItem.Text來檢索所選項目的值?沒有必要遍歷所有項目。 –

+1

您應該始終使用[_Parameterized queries_](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html)。這種代碼對[_SQL Injection_](http://en.wikipedia.org/wiki/SQL_injection)攻擊是開放的。 –

+0

只需在發生名爲Dropdownlist4_selectedIndexChanged的下拉列表中編寫ur代碼 –

回答

1

如果我理解你的問題清楚了,你只需要使用你的代碼在你的ListControl.SelectedIndexChanged事件。

當從列表控件的選擇在帖子 到服務器之間變化時發生。

<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True" 
     onselectedindexchanged="DropDownList4_SelectedIndexChanged" ...> 
</asp:DropDownList> 

protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ... 
} 

正如我在comment寫,你應該總是使用parameterized queries在你的SQL命令,你的代碼是開放的SQL Injection攻擊。

相關問題