我有一個列表視圖控件,我使用DataTable
進行綁定。在ItemDataBound
中,我創建了DropDownList
,並以編程方式添加項並將SelectedIndexChanged
事件綁定到該下拉列表。下拉列表SelectedIndexChanged事件處理程序在ListView控件內部多次觸發
在我的情況下,假設在ListView中創建了三行,並且在列表視圖中有三個Drop Downs。當我將下拉選擇更改爲第一個DropDownList
,然後SelectedIndexChanged
發生一次。然後我改變選擇在第二個DropDownList
然後SelectedIndexChanged
火兩次,然後我改變選擇在第二個DropDownList
然後SelectedIndexChanged
三次火災。
protected void dlMain_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView currentRow = (DataRowView)e.Item.DataItem;
Panel pnl = (Panel)e.Item.FindControl("pnlUser");
if (pnl != null)
{
pnl.Controls.Add(new LiteralControl(currentRow.Row.ItemArray[1].ToString()));
}
Panel pnlDropDown = (Panel)e.Item.FindControl("pnlDropDown");
if (pnlDropDown != null)
{
if (dtCustomers.Rows.Count > 0)
{
DataRow[] customers = dtCustomers.Select("KItemId = " + Convert.ToInt32(currentRow.Row.ItemArray[0]) + "");
if (customers.Length > 0)
{
DropDownList customerDDL = new DropDownList();
ListItem baseItem = new ListItem("-- Select --", "0");
customerDDL.Items.Add(baseItem);
foreach (DataRow customerRow in customers)
{
ListItem newItem = new ListItem(customerRow["CustName"].ToString(), customerRow["CustId"].ToString());
customerDDL.Items.Add(newItem);
}
customerDDL.ID = "Customers" + Convert.ToString(currentRow.Row.ItemArray[0]);
customerDDL.AutoPostBack = true;
customerDDL.SelectedIndexChanged += customerDDL_SelectedIndexChanged;
pnlDropDown.Controls.Add(customerDDL);
}
}
}
}
}
要檢查事件的行爲,我寫的一行代碼在SelectedIndexChanged
事件
void customerDDL_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList changedList = (DropDownList)sender;
}
這裏的時候,我的拳頭改變DropDown1的設定值然後我得到了ID
DropDown1然後我更改DropDown2的選定值該事件觸發兩次,並在第一次我得到發件人對象ID的DrowDown1,然後再次控制進來的事件,我得到發件人對象DropDown2。
我該怎麼做才能獲得SelectedIndexChanged
中的精確控制選定項目?
感謝您的回答,我嘗試了您的建議方式,但獲得了相同的結果。即當我將第二個下拉菜單中的部分更改下來時,事件觸發兩次。 :-( –
您可以發佈您的修改後的代碼.. –
您好先生,如果我放置了'Page.IsPostBack'條件,那麼當第一次頁面加載時控件的呈現消失 –