2016-12-02 98 views
-2

Click here to see the image如何在ASP.NET中單擊下拉列表時顯示金額?

我只是想顯示金額,每當我點擊下拉列表中的項目。

我想....

if(ddl.SelectedIndex == 1) 
{ 
    txtAmount.Text = "240"; 
} 

我用這個:

string SQL = @"SELECT Product FROM Supplies"; 

using (SqlCommand cmd = new SqlCommand(SQL, con)) 
{ 
    using (SqlDataReader dr = cmd.ExecuteReader()) 
    { 
     ddlProduct.DataSource = dr; 
     ddlProduct.DataTextField = "Product"; 
     ddlProduct.DataBind(); 
     ddlProduct.Items.Insert(0, new ListItem("Select one...", "")); 
    } 
+0

如何綁定下拉菜單? –

+0

我用這個 字符串SQL = @「SELECT Product FROM Supplies」; 使用(的SqlCommand CMD =新的SqlCommand(SQL,CON)) { 使用(SqlDataReader的DR = cmd.ExecuteReader()){ ddlProduct.DataSource =博士; ddlProduct.DataTextField =「Product」; ddlProduct.DataBind(); ddlProduct.Items.Insert(0,new ListItem(「Select one ...」,「」)); } –

+0

您的帖子下方有一個[編輯](http://stackoverflow.com/posts/40927246/edit)按鈕。請使用此功能將信息添加到您當前的帖子 –

回答

0

您可以從數據庫中選擇值字段並將其綁定到下拉列表如下

string SQL = @"SELECT Product, Price FROM Supplies"; 
using (SqlCommand cmd = new SqlCommand(SQL, con)) 
{ 
using (SqlDataReader dr = cmd.ExecuteReader()) 
{ 
    ddlProduct.DataSource = dr; 
    ddlProduct.DataTextField = "Product"; 
    ddlProduct.DataValueField = "Price "; 
    ddlProduct.DataBind(); 
    ddlProduct.Items.Insert(0, new ListItem("Select one...", "")); 
} 

然後,你可以得到的選擇值並設置文本框文本如下

protected void itemSelected(object sender, EventArgs e) 
{ 
    txtAmount.Text = ddlProduct.SelectedValue.ToString(); 
} 

因爲您需要在selectedindexchanged上添加事件

<asp:DropDownList ID="ddlProduct" runat="server" 
     onselectedindexchanged="itemSelected" AutoPostBack="True" > 
</asp:DropDownList> 
+0

非常感謝! –

+0

我可以再問一次嗎?抱歉 –

0

只寫下面的代碼selectedIndexChanged事件您dropdownlist

txtAmount.Text = ddlProduct.SelectedValue; 
+0

感謝您的幫助:) –

0

您添加OnSelectedIndexChanged事件到DropDownList並將AutoPostback設置爲true

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> 
    <asp:ListItem Text="Select one..." Value=""></asp:ListItem> 
    <asp:ListItem Text="Silk" Value="1"></asp:ListItem> 
    <asp:ListItem Text="Wool" Value="2"></asp:ListItem> 
    <asp:ListItem Text="Cotton" Value="3"></asp:ListItem> 
</asp:DropDownList> 

而且在後面的代碼

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    decimal amount = 0; 

    if (!string.IsNullOrEmpty(DropDownList1.SelectedValue)) 
    { 
     //get amount from somewhere 
     //amount = 
    } 

    txtAmount.Text = string.Format("{0:C}", amount); 
} 
+0

感謝您的幫助:) –