我設法覆蓋Boundfield以顯示一個下拉列表,如果我把它放在一個GridView中。ASP.NET Boundfield被覆蓋以支持Dropdownlist缺少一個最終特徵
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
Control child = null;
Control cellControl = null;
if ((((rowState & DataControlRowState.Edit) != DataControlRowState.Normal) && !this.ReadOnly)
|| ((rowState & DataControlRowState.Insert) != DataControlRowState.Normal))
{
// If data cell is in edit mode, create DropDownList editor for this cell
// and set data properties.
DropDownList box = new DropDownList();
box.Items.Add(DefaultValueText);
box.DataSource = this.GetDataSource();
box.DataMember = this.BusinessObjectName;
box.DataTextField = this.DataTextField;
box.DataValueField = this.DataValueField;
box.AppendDataBoundItems = true;
box.ToolTip = this.HeaderText;
cell.Controls.Add(box);
box.DataBind();
// if in edit mode, prepare dropdown for binding
if ((this.DataField.Length != 0) && ((rowState & DataControlRowState.Edit) != DataControlRowState.Normal))
{
cellControl = box;
}
}
else if (this.DataField.Length != 0) // if in read only mode, prepare cell for binding
{
cellControl = cell;
}
if ((cellControl != null) && base.Visible)
{
cellControl.DataBinding += new EventHandler(this.OnDataBindField);
}
}
protected override void OnDataBindField(object sender, EventArgs e)
{
Control control = (Control)sender;
Control namingContainer = control.NamingContainer;
object dataValue = this.GetValue(namingContainer);
bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
string str = this.FormatDataValue(dataValue, encode);
if (control is TableCell)
{
if (str.Length == 0)
{
str = " ";
}
((TableCell)control).Text = str;
}
else
{
//If data cell is in edit mode, set selected value of DropDownList
if (dataValue != null)
{
DropDownList dropDownList = (DropDownList) control;
ListItem itm = dropDownList.Items.FindByText(dataValue.ToString());
if (itm != null)
{
dropDownList.Text = itm.Value;
}
else
((DropDownList)control).Text = DefaultValueText;
}
}
}
的最後一項功能我加是如果沒有被選中,如「請選擇」,例如顯示默認值/附加項目。我可以通過OnDataBind事件中的屬性DefaultValueText來設置它。
現在,這裏是我面臨的問題:
在InitializeDataCell,如果我設置
box.AppendDataBoundItems = true;
,並呼籲
box.DataBind();
的下拉列表擁有的所有項目,加上其他默認項目。 它也可以在OnDataBind事件中很好地工作,如果數據綁定項不包含值,我現在可以選擇默認值。
但是,當顯示在GridView的下拉列表,它包含了從數據源的缺省值加兩遍,因爲我設置AppendDataBoundItems = true,這會導致不明確它的項目添加項目時,下拉 的gridview必須調用數據綁定兩次,但它只在OnDataBind事件方法中註冊一次。我只在那裏看到一個電話,在那一刻,一切都很好,下拉菜單中包含默認項目加上數據源中每個項目的一個。
任何建議我在哪裏或如何處理數據綁定,以便我完全控制數據綁定?
我看到影響數據綁定的唯一方法是通過將一個事件處理程序附加到DropDownList.DataBind ING。這隻被調用一次(從我在調試模式中看到的),那麼誰又是第二次複製這些項目? 與下拉列表關聯的getModes()方法接收的命中數等於我擁有的行數(每個dropdownlist初始化一次)。 它可能來自視圖狀態?如果可能的話,我想我可能會嘗試關閉它 – 2009-12-30 11:36:58