我正在通過呼叫存盤程序將值/文本串列加載到 asp:dropdownlist 中。我在 !Page.IsPostBack 塊內的 PageLoad 方法上填充下拉串列,如下所示:
if (!Page.IsPostBack)
{
GetDropDownLists();
DataBind();
}
這是我的后端代碼實作:
protected void GetDropDownLists()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("get_articletype", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
xArticleTypeList.Items.Clear();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
xArticleTypeList.SelectedIndex = 0;
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
}
如果我的代碼不在 !Page.IsPostBack 塊內,在我單擊保存按鈕后,默認值將始終是下拉串列的第一項。但是一旦我把我的代碼放在 !Page.IsPostBack 塊中,我的下拉串列就是空的。作為參考,這里是我的 asp:dropdownlist 的前端實作。
<asp:DropDownList ID="xArticleTypeList" EnableViewState="true" AutoPostBack="true" CssClass="form-control" runat="server" />
我知道還有其他主題涵蓋了這個問題,但沒有一個建議的解決方案對我有用。預先感謝您的意見。
uj5u.com熱心網友回復:
您的問題是您插入空白請在系結之前選擇行。結果,當您系結時,您正在吹掉下拉選單。
試試這個方法:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand("get_articletype", conn))
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dt.Load(cmd.ExecuteReader());
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
}
擺脫你額外的電話重新系結你有這個:
GetDropDownLists();
DataBind(); <--- remove unless you need, or execute BEFORE the GetDropDownList()
因此,將您的添加/插入空白行移至下拉串列以在下拉資料系結之后。
并洗掉你的 DataBind() - 你不需要它,如果出于某種原因你需要它,然后將 DataBind() 移動到你加載 GetDropDownLists() 之前 - 但我的猜測是你只是為了希望而放棄它使這項作業,它會導致組合框重新選擇 - 所以洗掉除非你給出一個真正好的高質量的輪廓和敘述你為什么在那里有 DataBin() 命令 - (但如前所述,如果您確實,但確實確實需要執行該 DataBind() 命令 - 在加載組合之前將其移至)。
因此,在后面添加空白行
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381704.html
