问题描述:在一页面上有一个dropdownlist、一个textbox、一个button。当页面加载的时候用If Not Me.IsPostBack然后从数据库中读取数据添加到dropdownlist和textbox。当点击button时把最新的数据写回到数据库里(dropdownlist选择新的项目,textbox写新的内容等等)。现在的问题是:页面load时候如果用If Not Me.IsPostBack,那么点击button的时候能够获取textbox的最新修改数据,但是dropdownlist不能获取(为空);
当页面load时候如果不用If Not Me.IsPostBack,那么可以获取dropdownlist和textbox的值,但都是老的数据。
现在我想在点击button的时候能获取dropdownlist和textbox的最新数据,应该怎么做?
谢谢!!
当页面load时候如果不用If Not Me.IsPostBack,那么可以获取dropdownlist和textbox的值,但都是老的数据。
现在我想在点击button的时候能获取dropdownlist和textbox的最新数据,应该怎么做?
谢谢!!
{
}
dropdownlist和textbox绑定数据都要放到上面代码里面
简单测试 <form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1"
runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection("server=localhost;database=northwind;uid=sa;pwd="))
{
SqlCommand cmd = new SqlCommand("select CategoryID, CategoryName from Categories", conn);
conn.Open();
DropDownList1.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryID";
DropDownList1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(DropDownList1.SelectedValue + ", " + TextBox1.Text);
}
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="false">
的话,会出现楼主那种取不到值的情况。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" EnableViewState="false" %>
也是同样会出现取不到DropDownList值的问题。看来,ViewState, ViewState.....
搞清楚ViewState太重要了。
经你这么一说,我确实想到我把这个改成false后就不行了
呵呵 多谢多谢!!!