[英]How to assign the selected value of Drop down to text box
每當我按下按鈕時,我都試圖在下拉列表文本框中分配選定的值。 我在TextBox
中看不到選定的值。 有人可以讓我知道我在想什么嗎?
我的代碼如下:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string strConn = "Initial Catalog=NavigateV6;Data Source=SVUSRYE-SQL3D1;User ID=dopis_user;Password=dopis_password;Persist Security Info=True;MultipleActiveResultSets=True";
SqlConnection mycn = new SqlConnection(strConn);
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select accountid FROM trn_account ", mycn);
myda.Fill(ds);
DDL.DataSource = ds;
DDL.DataTextField = "AccountID";
DDL.DataValueField = "AccountID";
DDL.DataBind();
}
protected void DDL_SelectedIndexChanged(Object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(TextBox1.Text))
TextBox1.Text = selectedValue;
}
}
ASPX:
<asp:DropDownList ID="DDL" runat="server" AutoPostBack="True" OnSelectedIndexChanged = " DDL_SelectedIndexChanged" >
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
Text="sumbit" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</asp:Content>
jQuery可以在沒有回發的情況下迅速完成此操作:
$('#<%= ButtonID.ClientID %>').click(function() {
$('#<%= TextBoxID.ClientID %>').val($('#<%= DDL_ID.ClientID %>').val());
return false;
});
實際上,您甚至不需要單擊按鈕,當用戶在ddl中選擇新值時可以完成此操作:
$('#<%= DDL_ID.ClientID %>').change(function() {
$('#<%= TextBoxID.ClientID %>').val($(this).val());
});
您的問題是因為當您檢查(!string.IsNullOrEmpty(TextBox1.Text))
,它總是返回false,因為在第一階段,TextBox的值為空,因此從不執行if condition
內部代碼...如果需要經過上述條件,可以在聲明時在TextBox
中添加一些值。
要么,
只需在DropDownList
SelectedIndexChanged
中這樣做即可
var selectedValue = ((DropDownList)sender).SelectedValue;
TextBox1.Text = selectedValue;
這是像您的代碼一樣的工作示例:
ASPX:
<body>
<form runat="server" id="form1">
<asp:DropDownList ID="DDL" runat="server" AutoPostBack="True"
OnSelectedIndexChanged = "DDL_SelectedIndexChanged" >
<asp:ListItem Value="One">One</asp:ListItem>
<asp:ListItem Value="Two">Two</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="sumbit" onclick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
</form>
</body>
背后的代碼:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
TextBox1.Text = selectedValue;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.