的DropDownList只选择第一值 [英] DropDownList only selects the first value
问题描述
我和我的DropDownList的一个问题。阅读张贴在这里的很多后,我仍然无法使工作,使病人问。
I have a problem with my DropDownList. after reading alot of post here i still cant make it work so ill ask.
这是我的C#code:
this is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection("Data Source=PCM13812;Initial Catalog=Newsletter;Integrated Security=True"))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("Select Email From Newsletter", connection);
EmailList.DataSource = cmd.ExecuteReader();
EmailList.DataTextField = "Email";
EmailList.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Vælg_Click(object sender, EventArgs e)
{
EmailListe .Text = EmailList.Text;
}
下面是我的ASP code:
Here is a my Asp code:
<asp:DropDownList ID="EmailList" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
<asp:Button runat="server" ID="Vælg" Text="Vælg Email" OnClick="Vælg_Click" />
<asp:TextBox runat="server" ID="EmailListe" TextMode="MultiLine" />
<asp:TextBox ID="Besked" runat="server" />
正如你可以看到我从我的SqlDatabase DropDownList的值。当我选择在DropDownList电子邮件并点击按钮,然后它总是第一个值添加到文本框,即使我选择另一个电子邮件。
As you can see I get the DropDownList value from my SqlDatabase. When I select an Email in the dropdownlist and click the button then it ALWAYS add the first Value to the textbox, even if I select another Email.
我在做什么错了?
推荐答案
只记得ASP.NET是如何工作的,的Page_Load
之前名为您每个服务器往返的事件处理程序列表,然后刷新为默认值。只是检查它不是一个回送:
Just remember how ASP.NET works, Page_Load
is called before your event handler for each server roundtrip then list is refreshed to default value. Just check it's not a postback:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
// Your code here
}
编辑:一个小小的建议;你不处理的SqlCommand
和 SQLReader的
,你应该提取值,并尽快处理掉以释放资源。这样,他们会被GC回收,这可能是一个大问题,特别是如果你的网站有繁忙的交通......
a small suggestion; you're not disposing SqlCommand
and SqlReader
, you should extract values and dispose them as soon as possible to free resources. This way they'll be collected by GC and this may be a big problem, especially if your site has heavy traffic...
这篇关于的DropDownList只选择第一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!