0
請幫我了以下問題:重新添加一個控制到控件集合問題
場景:
- 如果
ComboBox
不是null
:Controls.Remove(ComboBox)
,ComboBox.Dispose()
- 創建一個新的
ComboBox
(新的DataSource
,DisplayMember
等) - 添加新的
ComboBox
至Controls
:Controls.Add(ComboBox)
- 去1
問題: 當我重新加入我的ComboBox
(在地方新的屬性)到Controls
集合,性質上一ComboBox
的(準確ComboBox.Items
集合)被分配(覆蓋)到剛添加的新的。
你能提供給我任何建議什麼是(或可能)發生在這裏,請嗎?
感謝
C#代碼:
private void DropDownCell(CellIndex cell, object dropDownData, string displayMember) {
// Remove previous drop-down, if any
if(DropDownBox != null) {
var garbageDropDownBox = DropDownBox;
DropDownBox = null;
Controls.Remove(garbageDropDownBox);
garbageDropDownBox.Dispose();
}
// Create up the dropdown:
var dropDownBox = new ComboBox() {
DataSource = dropDownData,
DisplayMember = displayMember,
DropDownStyle = ComboBoxStyle.DropDown,
MaxDropDownItems = 25,
AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend,
Margin = new Padding(0, 0, 0, 0),
Font = new Font(Family, CellFont.Size, CellFont.Style, CellFont.Unit),
Location = Point.Round(GetViewPoint(GetLogicalCellRect(cell).Location))
};
// Set the background color
bool editable = true, editableKnown = true;
var brush = SheetStyle.GetBackBrush(source, source.GetColumn(cell.Column), cell.Row, ref editableKnown, ref editable) as SolidBrush;
if(brush != null)
dropDownBox.BackColor = brush.Color;
// Tie up events to the drop down
dropDownBox.SelectionChangeCommitted += new EventHandler(delegate(object sender, EventArgs e) {
if(sender == DropDownBox)
try {
source.GetColumn(cell.Column).SetDropDownItem(cell.Row, dropDownBox.SelectedItem);
} catch(Exception ex) {
Logger.Debug(ex);
}
});
dropDownBox.DropDownClosed += new EventHandler(delegate(object sender, EventArgs e) {
if(sender == DropDownBox)
try {
dropDownBox.Visible = false;
Focus();
//FocusIndex = cell;
} catch {
}
});
// Add the control and calculate the optimal width based on contents
Controls.Add(dropDownBox);
object currentValue = source.GetColumn(cell.Column).GetRawValue(cell.Row);
using(Graphics g = dropDownBox.CreateGraphics()) {
float width = dropDownBox.Width - SystemInformation.VerticalScrollBarWidth;
foreach(DataRowView item in dropDownBox.Items) {
if(object.Equals(item[displayMember], currentValue))
dropDownBox.SelectedItem = item;
width = Math.Max(width, g.MeasureString(dropDownBox.GetItemText(item), dropDownBox.Font).Width);
}
dropDownBox.Width = (int)width + SystemInformation.VerticalScrollBarWidth;
}
// Scroll to drop down and open it
ScrollToCell(cell);
dropDownBox.DroppedDown = true;
dropDownBox.Focus();
DropDownBox = dropDownBox;
}
顯示部分代碼和標記。 –
出於興趣,爲什麼不能更新屬性?因爲它是一個UI控件,它不應該被破壞和重新創建... – Deanna
@Tomas:我已經添加了做這件事的方法。 (對不起,我不知道如何在SO中格式化一個代碼塊) –