如何从下拉列表中检索文本?

时间:2013-04-15 06:44:15

标签: c# asp.net sql

我必须审核数据库中的更改。在大多数页面上,这都很完美,因为只有文本框 - 但是在我正在处理的页面上,使用下拉列表,我的代码无效。

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

1 个答案:

答案 0 :(得分: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 中所写的那样,你应该总是在你的sql命令中使用 parameterized queries ,你的代码是为打开的> SQL Injection 攻击。

相关问题