Пожалуйста, помогите мне решить следующую проблему:
Сценарий:
- Если
ComboBox
не null
: Controls.Remove(ComboBox)
, ComboBox.Dispose()
- Создать новый
ComboBox
(с новыми DataSource
, DisplayMember
и т. Д.)
- Добавить новый
ComboBox
к Controls
: Controls.Add(ComboBox)
- перейти к 1.
Вопрос:
Когда я повторно добавляю свой ComboBox
(с новыми свойствами на месте) в коллекцию Controls
, свойства (в точности ComboBox.Items
коллекция) предыдущего ComboBox
назначаются (переопределяются) новому добавленному. 1029 *
Можете ли вы дать мне какие-либо предположения о том, что (или может) здесь происходит, пожалуйста?
Спасибо
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;
}