ListBox and ComboBox Controls
How to: Add and Clear Items in a ListBox Control
This example adds the contents of a Windows Forms TextBox control to a ListBox control when you click button1, and clears the contents when you click button2.
Example
private void button1_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add("Sally");
listBox1.Items.Add("Craig");
}
private void button2_Click(object sender, System.EventArgs e)
{
listBox1.Items.Clear();
}
Compiling the Code
This example requires:
A form with a ListBox control named
listBox1
and two buttons named button1 and button2. Add the button1Click
event handler tobutton1_Click
, and the button2Click
event handler tobutton2_Click
.
ListBoxиComboBox
Добавление и удаление элементов в элементе управления "ListBox"
В этом примере содержимое элемента управления TextBox Windows Forms добавляется7 в элемент управления ListBox при нажатии кнопки button1, а удаляется при нажатии кнопки button2.
Пример
private void button1_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add("Sally");
listBox1.Items.Add("Craig");
}
private void button2_Click(object sender, System.EventArgs e)
{
listBox1.Items.Clear();
}
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма с элементом управления ListBox с именем listBox1 и две кнопки с именами button1 и button2. Добавьте обработчик событий Click button1 в button1_Click и обработчик событий Click button2 в button2_Click.
How to: Determine the Selected Item in a ListBox Control
This example determines which item has been selected in a Windows Forms ListBox control.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
listBox1.Items.Add("One");
listBox1.Items.Add("Two");
listBox1.Items.Add("Three");
}private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if ((string)listBox1.SelectedItem == "Two")
MessageBox.Show((string)listBox1.SelectedItem);
}
Compiling the Code
This example requires:
A form named
Form1
with a ListBox control namedlistBox1
. Set the Load event handler of Form1 toForm1_Load
. Set the SelectedIndexChanged event handler oflistBox1
tolistBox1_SelectedIndexChanged
.
Note:
This code can also be used with a ComboBox control by substituting a ComboBox control named comboBox1 for the ListBox control and changing the code from listBox1 to comboBox1.
Определение выбранных элементов в элементе управления "ListBox"
В этом примере определяется, какой элемент был выбран в элементе управления ListBox Windows Forms.
Пример
private void Form1_Load(object sender, System.EventArgs e) { listBox1.Items.Add("One"); listBox1.Items.Add("Two"); listBox1.Items.Add("Three"); }
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e) { if ((string)listBox1.SelectedItem == "Two") MessageBox.Show((string)listBox1.SelectedItem); } |
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма с именем Form1 с элементом управления ListBox с именем listBox1. Установите обработчик событий Form1 Load в Form1_Load. Задайте обработчику событий SelectedIndexChanged для listBox1 значение listBox1_SelectedIndexChanged.8
Примечание.
Код также можно использовать с элементом управления ComboBox, заменив элемент управления ListBox на элемент управления ComboBox с именем comboBox1 и изменив в коде имя с listBox1 на comboBox1.
How to: Populate a ListBox Control with an Array of Strings
This example adds an array of strings to a ListBox control when the Windows Form opens.
Example
private void Form1_Load(object sender, System.EventArgs e) { string [] myList = new string[4]; myList[0] = "One"; myList[1] = "Two"; myList[2] = "Three"; myList[3] = "Four"; listBox1.Items.AddRange(myList); } |
Compiling the Code
This example requires:
A form named
Form1
with a ListBox control namedlistBox1
. Set the Load event handler ofForm1
toForm1_Load
.
This code can also be used with a ComboBox control by substituting a ComboBox control named |
Robust Programming
The following conditions may cause an exception:
The array contains one or more null values.
Заполнение элемента управления "ListBox" массивом строк
В этом примере массив строк добавляется в элемент управления ListBox при открытии формы Windows Form.
Пример
private void Form1_Load(object sender, System.EventArgs e) { string [] myList = new string[4]; myList[0] = "One"; myList[1] = "Two"; myList[2] = "Three"; myList[3] = "Four"; listBox1.Items.AddRange(myList); } |
Компиляция кода
Для этого примера необходимы следующие компоненты.
Форма с именем Form1 с элементом управления ListBox с именем listBox1. Задайте обработчику событий Load для Form1 значение Form1_Load.
Код также можно использовать с элементом управления ComboBox, заменив элемент управления ListBox на элемент управления ComboBox с именем comboBox1 и изменив в коде имя с listBox1 на comboBox1. |
Надежное программирование
Исключение может возникнуть при следующих условиях.
В массиве содержится одно или несколько значений NULL.
How to: Search for an Item in a ListBox Control
In this example, you add some items to a Windows Forms ListBox control when the form is loaded. Then you search the ListBox for a specific item by clicking a button on the form. If the item is found, it is selected and a success message, which contains the item and its index, is sent by using a message box. Otherwise, an "Item not found" message is sent.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
listBox1.Items.Add("Angelina");
listBox1.Items.Add("Isabella");
listBox1.Items.Add("Sarah");
}
private void button1_Click(object sender, System.EventArgs e)
{
// Set the search string:
string myString = "Isabella";
// Search starting from index -1:
int index = listBox1.FindString(myString, -1);
if (index != -1)
{
// Select the found item:
listBox1.SetSelected(index,true);
// Send a success message:
MessageBox.Show("Found the item \"" + myString + "\" at index: " + index);
}
else
MessageBox.Show("Item not found.");
}
- Введение в язык c# и .Net Framework
- Язык c#
- Архитектура платформы .Net Framework
- Creating Your First c# Application
- To create a c# application
- Создание первого приложенияC#
- Создание приложения c#
- To create a c# console application
- Создание консольного приложения c#
- To create a c# Windows application
- Создание приложений Windows Forms на c#
- Introduction to Windows Presentation Foundation
- To create a wpf application
- Создание приложения wpf c#
- To create event handlers
- Создание обработчиков событий
- Designing a User Interface in Visual c#
- Adding Controls
- Создание пользовательского интерфейса в Visual c#
- Добавление элементов управления
- Setting Properties
- Handling Events
- Задание свойств
- Обработка событий
- How to: Use Button Controls
- Использование элемента управления "Button"
- To use buttons in a program
- Использование кнопок в программе
- How to: Call a Button's Click Event Programmatically
- To use buttons in a program
- Программный вызов события нажатия кнопки
- Использование кнопок в программе
- How to: Create a Group of Radio Buttons from a String Array
- Compiling the Code
- Example
- Создание группы переключателей из массива строк
- Создание непрямоугольной кнопки
- Компиляция кода
- How to: Display Text on a Windows Form
- To display text in a label
- Отображение текста в форме Windows Forms
- Отображение текста в надписи
- How to: Use TextBox Controls to Get User Input
- Использование элемента управления "TextBox" для получения вводимых данных
- To retrieve input typed in a text box
- Извлечение введенных в текстовое поле данных
- How to: Convert the Text in a TextBox Control to an Integer
- Диалоговые окна Извлечение данных из диалогового окна
- To create the main form of your application
- To create a dialog box
- Создание основной формы приложения
- Создание диалогового окна
- Retrieving Data from a Dialog Box
- To retrieve data from a dialog box.
- Извлечение данных из диалогового окна
- How to: Browse a Folder
- To display the folder browser dialog box
- Просмотр папки
- Отображение диалогового окна обозревателя папок
- How to: Save a File to a Folder
- To display the folder browser dialog box
- Сохранение файла в папку
- Отображение диалогового окна обозревателя папок
- How to: Display a List of Fonts
- To display the font dialog box
- Отображение списка шрифтов
- Отображение диалогового окна выбора шрифта
- How to: Display an OpenFileDialog Dynamically
- Отображение цветовой палитры
- Отображение диалогового окно выбора цвета
- ListBox and ComboBox Controls
- Compiling the Code
- Отображение даты и времени в приложении
- Отображение даты с помощью элемента управления "MonthCalendar"
- To display the time by using a DateTimePicker control
- Отображение времени с помощью элемента управления "DateTimePicker"
- How to: Determine the Span Between Two Dates
- Создание настраиваемого пользовательского интерфейса
- Добавление панелей инструментов в приложение Windows Forms
- To add a set of standard toolbar button
- Добавление набора стандартных кнопок панели инструментов
- How to: Create a Tooltip for a Control
- Compiling the Code
- Compiling the Code
- Добавление элементов управления Windows Forms во время выполнения
- Компиляция кода15
- Accessing and Displaying Data
- How to: Write Class Data to an xml File
- Example
- Compiling the Code
- Compiling the Code
- Robust Programming
- Чтение xml из файла
- Пример18
- Компиляция кода
- Надежное программирование
- How to: Read Class Data from an xml File
- Example
- Compiling the Code
- Robust Programming
- Чтение данных класса из xml-файла
- Пример19
- Компиляция кода
- Compiling the Code
- Компиляция кода
- Compiling the Code
- Robust Programming
- Рисование кривой в форме
- Компиляция кода
- Надежное программирование
- How to: Draw Outlined Shapes
- Example
- Compiling the Code
- Robust Programming
- Рисование контурных фигур
- Пример23
- Компиляция кода
- Добавление файлов мультимедиа в приложение
- Внедрение проигрывателя Windows Media в форму
- Добавление элемента управления "Windows Media Player" в панель элементов.
- To add the Windows Media Player control to a Windows Form
- Добавление элемента управления "Windows Media Player" в форму Windows Forms
- How to: Play Sounds in an Application
- To play an audio file
- Воспроизведение звука в приложении
- Воспроизведение аудиофайла
- Creating and Using Bitmaps and Icons
- How to: Create a Bitmap at Run Time
- Example
- Создание и использование точечных рисунков и значков
- Создание точечного рисунка во время выполнения
- Compiling the Code
- Compiling the Code
- Создание приложений wpf
- Создание пользовательского интерфейса для приложения wpf
- To create a wpf application
- Создание приложения wpf
- Adding Controls to the wpf Window You can add controls to the wpf window by dragging them from the Toolbox. To add a control to the wpf window
- Добавление элементов управления в окно wpf
- Добавление элемента управления в окно wpf
- Common wpf Controls
- Procedure To add a control to the wpf window
- Стандартные элементы управления wpf
- Процедура Добавление элемента управления в окно wpf
- Standard wpf Controls
- Стандартные элементы управления wpf
- How to: Create Event Handlers for wpf Controls
- To create an event handler for a button
- Создание обработчиков событий для элементов управления wpf
- Создание обработчика событий для кнопки
- Connecting to Data
- How to: Connect to a Database
- To add a connection to the Northwind database
- Подключение к данным
- Подключение к базе данных
- Добавление подключения к базе данных "Northwind"
- How to: Display Related Data on a Form
- To display related data on a form
- Отображение связанных данных в форме
- Отображение связанных данных в форме
- Using linq in c# Express
- Advantages of Using linq
- Использование linq в c# Express
- Преимущества использования linq
- C# Language Enhancements that Support linq
- Расширения языка c# для поддержки linq
- Writing linq Queries
- Linq to Objects
- Написание запросов linq
- Linq to Objects
- Linq to sql
- Linq to DataSet
- Linq to xml
- Linq to sql
- Linq to DataSet
- ЯзыкC# для начинающих Структура программы c#
- "Hello World" в стиле c#
- Using Directives and Namespaces
- Comments
- Директивыusingи пространства имен
- Комментарий
- Classes
- Console Input and Output
- Консольный ввод и вывод
- Program Structure and Flow of Execution
- Windows Forms Applications
- Структура программы и ход выполнения
- Приложения Windows Forms36
- Console Applications
- Namespaces
- Консольные приложения
- Пространства имен
- Namespace Shortcuts
- Creating Your Own Namespace
- Ускоренный доступ к содержимому пространства имен
- Создание собственного пространства имен
- Example
- Classes
- Classes vs. Objects
- Классы и объекты
- Static vs. Instance Members
- Classes vs. Files
- Члены экземпляра и статические члены37
- Классы и файлы
- Encapsulation
- Инкапсуляция
- Inheritance
- Polymorphism
- Наследование
- Полиморфизм
- Constructors
- Конструкторы
- Operator Overloading
- Compiling the Code
- Имитация параметров по умолчанию
- Компиляция кода
- Переменные и константы
- Constants
- Built-in Data Types
- Константы
- Встроенные типы данных
- Using Built-in Data Types
- Типы значений и ссылочные типы
- Boxing and Unboxing
- Упаковка и распаковка
- Performance issues
- Проблемы производительности
- Operators
- Decisions and Branching
- Remarks
- Выбор и ветвление
- Foreach Loops
- Циклы foreach
- For Loops
- Working with Strings
- Доступ к отдельным знакам
- Changing Case
- Смена регистра
- Comparisons
- Сравнения
- Splitting a String into Substrings
- Разделение строки на подстроки
- Using StringBuilder
- Использование класса StringBuilder
- How to: Generate Multiline String Literals
- Массивы и коллекции
- Массивы
- Одномерные массивы
- Multidimensional Arrays
- Jagged Arrays
- Многомерные массивы
- Массивы массивов
- Using the foreach Statement
- Использование оператора foreach
- Arrays of Objects
- Массивы объектов
- How to: Declare an Array
- Compiling the Code
- Robust Programming
- Инициализация массива
- Компиляция кода
- Коллекции
- How to: Iterate Through an Array
- Compiling the Code
- Компиляция кода
- Enumerations
- Перечисления
- More Advanced Enumeration Techniques
- Try and Catch
- Обработка ошибок и исключений
- Try и Catch
- Finally Blocks
- Using Exception Handling
- You can also cause your own exceptions using the throw keyword.
- Блоки finally
- How to: Catch an Exception
- Example
- Compiling the Code
- Перехват исключения
- Компиляция кода
- .Net Framework Conceptual Overview
- Общие сведения об основных понятиях платформы .Net Framework
- Features of the Common Language Runtime
- Возможности среды clr
- .Net Framework Class Library
- Библиотека классов платформы .Net Framework