我试图在按下按钮时在下拉菜单中分配所选值。我无法在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>
答案 0 :(得分:1)
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());
});
答案 1 :(得分:0)
你的问题是因为当你检查(!string.IsNullOrEmpty(TextBox1.Text))
时,它总是返回false,因为在第一阶段,TextBox的值为空,因此永远不会执行if condition
的内部代码.....如果你需要经历上述条件,你可以在声明时在TextBox
中加上一些价值.......
或者,
只需在SelectedIndexChanged
DropDownList
中执行此操作即可
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;
}
}