2016-12-02 58 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

感谢您的帮助:) –

相关问题