ListBox.ObjectCollection.Add(Object) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Добавляет элемент в список элементов для ListBoxэлемента.
public:
int Add(System::Object ^ item);
public int Add(object item);
member this.Add : obj -> int
Public Function Add (item As Object) As Integer
Параметры
- item
- Object
Объект, представляющий элемент, добавляемый в коллекцию.
Возвращаемое значение
Отсчитываемый от нуля индекс элемента в коллекции или -1, если BeginUpdate() он был вызван.
Исключения
Недостаточно места для добавления нового элемента в список.
item равно null.
Примеры
В следующем примере кода показано, как создать ListBox элемент управления, который отображает несколько элементов в столбцах и может иметь несколько элементов, выбранных в списке элементов. Код для примера добавляет 50 элементов в ListBoxAdd метод ListBox.ObjectCollection класса, а затем выбирает три элемента из списка с помощью SetSelected метода. Затем код отображает значения из ListBox.SelectedObjectCollection коллекции (через SelectedItems свойство) и ListBox.SelectedIndexCollection (через SelectedIndices свойство). В этом примере требуется, чтобы код находился в и вызывается из .Form
void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
// Create an instance of the ListBox.
ListBox^ listBox1 = gcnew ListBox;
// Set the size and location of the ListBox.
listBox1->Size = System::Drawing::Size( 200, 100 );
listBox1->Location = System::Drawing::Point( 10, 10 );
// Add the ListBox to the form.
this->Controls->Add( listBox1 );
// Set the ListBox to display items in multiple columns.
listBox1->MultiColumn = true;
// Set the selection mode to multiple and extended.
listBox1->SelectionMode = SelectionMode::MultiExtended;
// Shutdown the painting of the ListBox as items are added.
listBox1->BeginUpdate();
// Loop through and add 50 items to the ListBox.
for ( int x = 1; x <= 50; x++ )
{
listBox1->Items->Add( String::Format( "Item {0}", x ) );
}
listBox1->EndUpdate();
// Select three items from the ListBox.
listBox1->SetSelected( 1, true );
listBox1->SetSelected( 3, true );
listBox1->SetSelected( 5, true );
#if defined(DEBUG)
// Display the second selected item in the ListBox to the console.
System::Diagnostics::Debug::WriteLine( listBox1->SelectedItems[ 1 ] );
// Display the index of the first selected item in the ListBox.
System::Diagnostics::Debug::WriteLine( listBox1->SelectedIndices[ 0 ] );
#endif
}
private void button1_Click(object sender, System.EventArgs e)
{
// Create an instance of the ListBox.
ListBox listBox1 = new ListBox();
// Set the size and location of the ListBox.
listBox1.Size = new System.Drawing.Size(200, 100);
listBox1.Location = new System.Drawing.Point(10,10);
// Add the ListBox to the form.
this.Controls.Add(listBox1);
// Set the ListBox to display items in multiple columns.
listBox1.MultiColumn = true;
// Set the selection mode to multiple and extended.
listBox1.SelectionMode = SelectionMode.MultiExtended;
// Shutdown the painting of the ListBox as items are added.
listBox1.BeginUpdate();
// Loop through and add 50 items to the ListBox.
for (int x = 1; x <= 50; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
// Allow the ListBox to repaint and display the new items.
listBox1.EndUpdate();
// Select three items from the ListBox.
listBox1.SetSelected(1, true);
listBox1.SetSelected(3, true);
listBox1.SetSelected(5, true);
// Display the second selected item in the ListBox to the console.
System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString());
// Display the index of the first selected item in the ListBox.
System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString());
}
Private Sub button1_Click(sender As Object, e As System.EventArgs)
' Create an instance of the ListBox.
Dim listBox1 As New ListBox()
' Set the size and location of the ListBox.
listBox1.Size = New System.Drawing.Size(200, 100)
listBox1.Location = New System.Drawing.Point(10, 10)
' Add the ListBox to the form.
Me.Controls.Add(listBox1)
' Set the ListBox to display items in multiple columns.
listBox1.MultiColumn = True
' Set the selection mode to multiple and extended.
listBox1.SelectionMode = SelectionMode.MultiExtended
' Shutdown the painting of the ListBox as items are added.
listBox1.BeginUpdate()
' Loop through and add 50 items to the ListBox.
Dim x As Integer
For x = 1 To 50
listBox1.Items.Add("Item " & x.ToString())
Next x
' Allow the ListBox to repaint and display the new items.
listBox1.EndUpdate()
' Select three items from the ListBox.
listBox1.SetSelected(1, True)
listBox1.SetSelected(3, True)
listBox1.SetSelected(5, True)
' Display the second selected item in the ListBox to the console.
System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems(1).ToString())
' Display the index of the first selected item in the ListBox.
System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices(0).ToString())
End Sub
Комментарии
Sorted Если для свойства ListBox задано trueзначение, элемент вставляется в список в алфавитном порядке. В противном случае элемент вставляется в конце списка. Чтобы вставить элемент в поле списка по определенной позиции, используйте Insert этот метод. Чтобы добавить набор элементов в поле списка в одной операции, используйте AddRange этот метод. Если вы хотите использовать Add метод для добавления большого количества элементов в список, используйте BeginUpdate методы и EndUpdate методы, чтобы предотвратить ListBox повторение при каждом добавлении элемента в список до тех пор, пока все элементы не будут добавлены в список. При добавлении элементов в ListBoxэлемент более эффективно отсортировать элементы, а затем добавить новые элементы.
При добавлении объекта в коллекцию ListBox сначала проверяет, имеет ли DisplayMember свойство ListControl класса имя члена из объекта, указанного для ссылки при получении текста элемента. DisplayMember Если свойство не имеет указанного элемента, ListBox то вызывает ToString метод объекта для получения текста, отображаемого в списке.