Помечаемый список позволяет пользователю выбрать несколько элементов, включив флажки, расположенные рядом с элементом.
Помечаемый список позволяет выбрать, добавить или удалить элементы из списка.
Помечаемый список позволяет выбрать, добавить или удалить элементы из списка.
добавление данных
добавление и удаление данных программно
выбор всех данных программно
сортировка
заполняем элемент данными с разных источников данных
добавление и удаление данных программно
выбор всех данных программно
сортировка
заполняем элемент данными с разных источников данных
добавление данных
Добавить данные можно с помощью диалогового окна или конструктора формы.
Выберите свойство Items и нажмите на кнопку или раскройте треугольник в элементе и нажмите на Edit Items, появится диалоговое окно, где можно добавить данные.
После того, как пользователь выберет данные и нажмет на кнопку ОК, выбранные данные отобразятся в элементах RichTextBox, TextBox и ListBox.
Выберите свойство Items и нажмите на кнопку или раскройте треугольник в элементе и нажмите на Edit Items, появится диалоговое окно, где можно добавить данные.
После того, как пользователь выберет данные и нажмет на кнопку ОК, выбранные данные отобразятся в элементах RichTextBox, TextBox и ListBox.
Form1.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0029 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
//добавляем данные -
checkedListBox1.Items.Add("yellow"); -
checkedListBox1.Items.Add("black"); -
checkedListBox1.Items.Add("white"); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
foreach(stringiincheckedListBox1.CheckedItems) { -
richTextBox1.Text += i +"\n"; -
textBox1.Text += i +"\r\n"; -
listBox1.Items.Add(i); -
} -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0029 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
//добавляем данные -
checkedListBox1.Items.Add("yellow"); -
checkedListBox1.Items.Add("black"); -
checkedListBox1.Items.Add("white"); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
foreach(stringiincheckedListBox1.CheckedItems) { -
richTextBox1.Text += i +"\n"; -
textBox1.Text += i +"\r\n"; -
listBox1.Items.Add(i); -
} -
} -
} }
добавление и удаление данных программно
Form1.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0030 {-
publicpartialclassForm1 : Form { -
//промежуточное свойство, которому будут передаваться данные из дочерней формы -
publicCheckedListBox Between { -
set{ -
checkedListBox1.Items.Add(value); -
} -
get{ -
returncheckedListBox1; -
} -
} -
publicForm1() { -
InitializeComponent(); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
//открываем дочернюю форму и передаем ей ссылку -
newForm2().ShowDialog(this); -
} -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно проиводить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
//удаляем все данные -
checkedListBox1.Items.Clear(); -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0030 {-
publicpartialclassForm1 : Form { -
//промежуточное свойство, которому будут передаваться данные из дочерней формы -
publicCheckedListBox Between { -
set{ -
checkedListBox1.Items.Add(value); -
} -
get{ -
returncheckedListBox1; -
} -
} -
publicForm1() { -
InitializeComponent(); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
//открываем дочернюю форму и передаем ей ссылку -
newForm2().ShowDialog(this); -
} -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно проиводить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
//удаляем все данные -
checkedListBox1.Items.Clear(); -
} -
} }
Form2.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0030 {-
publicpartialclassForm2 : Form { -
publicForm2() { -
InitializeComponent(); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
/*создаем переменную родительской формы (Form1)и присваиваем -
ей значение через ссылку на родительскую форму*/ -
Form1 F1 = (Form1)this.Owner; -
//присваиваем значение свойству в родительской форме -
//F1.Between.Text = textBox1.Text; -
F1.Between.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//передаем фокус -
textBox1.Select(); -
} -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//закрываем форму -
this.Close(); -
} -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0030 {-
publicpartialclassForm2 : Form { -
publicForm2() { -
InitializeComponent(); -
} -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
/*создаем переменную родительской формы (Form1)и присваиваем -
ей значение через ссылку на родительскую форму*/ -
Form1 F1 = (Form1)this.Owner; -
//присваиваем значение свойству в родительской форме -
//F1.Between.Text = textBox1.Text; -
F1.Between.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//передаем фокус -
textBox1.Select(); -
} -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//закрываем форму -
this.Close(); -
} -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
} }
выбор всех данных программно
Form1.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0031 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//кнопка Добавить -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//после нажатия кнопки Добавить активируем текстовое поле для ввода данных -
textBox1.Select(); -
} -
//текстовое поле для ввода данных -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
//кнопка Удалить -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно производить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
//кнопка Удалить все -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Clear(); -
} -
//кнопка Выбрать все -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
checkedListBox1.SetItemChecked(i,true); -
} -
} -
//кнопка Сбросить все -
privatevoidbutton5_Click(objectsender, EventArgs e) { -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
checkedListBox1.SetItemChecked(i,false); -
} -
} -
//кнопка OK -
privatevoidbutton6_Click(objectsender, EventArgs e) { -
//заполняем выбранными данными текстовые поля и список -
foreach(stringiincheckedListBox1.CheckedItems) { -
richTextBox1.Text += i +"\n"; -
textBox2.Text += i +"\r\n"; -
listBox1.Items.Add(i); -
} -
} -
//кнопка Clear -
privatevoidbutton7_Click(objectsender, EventArgs e) { -
//удаляем все данные из текстовых полей и списка -
richTextBox1.Clear(); -
textBox2.Clear(); -
listBox1.Items.Clear(); -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0031 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//кнопка Добавить -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//после нажатия кнопки Добавить активируем текстовое поле для ввода данных -
textBox1.Select(); -
} -
//текстовое поле для ввода данных -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
//кнопка Удалить -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно производить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
//кнопка Удалить все -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Clear(); -
} -
//кнопка Выбрать все -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
checkedListBox1.SetItemChecked(i,true); -
} -
} -
//кнопка Сбросить все -
privatevoidbutton5_Click(objectsender, EventArgs e) { -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
checkedListBox1.SetItemChecked(i,false); -
} -
} -
//кнопка OK -
privatevoidbutton6_Click(objectsender, EventArgs e) { -
//заполняем выбранными данными текстовые поля и список -
foreach(stringiincheckedListBox1.CheckedItems) { -
richTextBox1.Text += i +"\n"; -
textBox2.Text += i +"\r\n"; -
listBox1.Items.Add(i); -
} -
} -
//кнопка Clear -
privatevoidbutton7_Click(objectsender, EventArgs e) { -
//удаляем все данные из текстовых полей и списка -
richTextBox1.Clear(); -
textBox2.Clear(); -
listBox1.Items.Clear(); -
} -
} }
сортировка
Если задать свойству Sorted значение true, данные будут отсортированы, а вот после того, как данные будут отсортированы, задать свойству Sorted значение false, то данные первоначальный несортированный вид, ПОЧЕМУ-ТО не принимают.
Form1.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0032 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//текстовое поле для ввода данных -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
//кнопка Добавить -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//после нажатия кнопки Добавить активируем текстовое поле для ввода данных -
textBox1.Select(); -
} -
//кнопка Удалить -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно производить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
//кнопка Удалить все -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Clear(); -
} -
//кнопка OK -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
//заполняем выбранными данными текстовое поле -
foreach(stringiincheckedListBox1.CheckedItems) { -
textBox2.Text += i +"\r\n"; -
} -
} -
//кнопка Clear -
privatevoidbutton5_Click(objectsender, EventArgs e) { -
//удаляем все данные из текстового поля -
textBox2.Clear(); -
} -
//флажок -
privatevoidcheckBox1_CheckedChanged(objectsender, EventArgs e) { -
checkedListBox1.Sorted =true; -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace_0032 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//текстовое поле для ввода данных -
privatevoidtextBox1_KeyPress(objectsender, KeyPressEventArgs e) { -
if(e.KeyChar == (char)Keys.Enter) { -
//после нажатия клавиши Enter активируем кнопку OK -
button1.Select(); -
//перехватываем нажатие клавиши, удаляем системный звук -
e.Handled =true; -
} -
} -
//кнопка Добавить -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Add(textBox1.Text); -
//очищаем поле ввода -
textBox1.Clear(); -
//после нажатия кнопки Добавить активируем текстовое поле для ввода данных -
textBox1.Select(); -
} -
//кнопка Удалить -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//удаляем выбранные данные -
//удаление нужно производить с конца списка -
for(inti = checkedListBox1.Items.Count - 1; i >= 0; i--) { -
if(checkedListBox1.GetItemChecked(i)) -
checkedListBox1.Items.RemoveAt(i); -
} -
} -
//кнопка Удалить все -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
checkedListBox1.Items.Clear(); -
} -
//кнопка OK -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
//заполняем выбранными данными текстовое поле -
foreach(stringiincheckedListBox1.CheckedItems) { -
textBox2.Text += i +"\r\n"; -
} -
} -
//кнопка Clear -
privatevoidbutton5_Click(objectsender, EventArgs e) { -
//удаляем все данные из текстового поля -
textBox2.Clear(); -
} -
//флажок -
privatevoidcheckBox1_CheckedChanged(objectsender, EventArgs e) { -
checkedListBox1.Sorted =true; -
} -
} }
заполняем элемент данными с разных источников данных
В данном примере, наш элемент будет заполнен данными из: коллекции, текстового документа, XML файла, базы данных.
Form1.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;//подключить пространство именusingSystem.IO;//подключить пространство имен для кодировкиusingSystem.Text;//подключить пространство именusingSystem.Xml;//подключить пространство именusingSystem.Data.SqlClient;namespace_0033 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//заполняем данными из коллекции -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
List<string> Array =newList<string> { -
"red", -
"green", -
"blue" -
}; -
foreach(stringiinArray) { -
checkedListBox1.Items.Add(i); -
} -
} -
//заполняем данными из текстового файла -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//путь -
stringpath =@"TextFile1.txt"; -
//если файл существует -
if(File.Exists(path)) { -
//создаем байтовый поток и привязываем его к файлу -
//в конструкторе указываем: путь кодировка -
using(StreamReader sr =newStreamReader(path, Encoding.UTF8)) { -
while(!sr.EndOfStream) { -
checkedListBox2.Items.Add(sr.ReadLine()); -
} -
} -
} -
else{ -
MessageBox.Show("Такой файл не существует!"); -
} -
} -
//заполняем данными из XML файла -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
//путь -
stringpath =@"XMLFile1.xml"; -
//если файл существует -
if(File.Exists(path)) { -
XmlDocument XmlDoc =newXmlDocument(); -
//загружаем XML документ -
XmlDoc.Load(path); -
//получаем все дочерние элементы корневого элемента -
//xmlDoc.DocumentElement - корневой элемент -
foreach(XmlNode iinXmlDoc.DocumentElement.ChildNodes) { -
foreach(XmlNode jini.ChildNodes) { -
checkedListBox3.Items.Add(j.InnerText); -
} -
} -
} -
else{ -
MessageBox.Show("Такой файл не существует!"); -
} -
} -
//заполняем данными из базы данных -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
//строка подключения к источнику данных -
stringconnectSting =@"Data Source=.\MSSQLSERVER2012;Initial Catalog=star;Integrated Security=True"; -
//sql запрос -
stringsql ="select Color from Colors"; -
//создаем подключение -
using(SqlConnection myConnection =newSqlConnection(connectSting)) { -
//применяем запрос к источнику данных -
SqlCommand myCommand =newSqlCommand(sql, myConnection); -
try{ -
//открываем соединение -
myConnection.Open(); -
//создаем объект для извлечения данных -
SqlDataReader myReader = myCommand.ExecuteReader(); -
//извлекаем данные -
while(myReader.Read()) { -
checkedListBox4.Items.Add(myReader[0]); -
} -
} -
catch(Exception ex) { -
MessageBox.Show(" Соединение не установлено!"); -
} -
} -
} -
} }
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;//подключить пространство именusingSystem.IO;//подключить пространство имен для кодировкиusingSystem.Text;//подключить пространство именusingSystem.Xml;//подключить пространство именusingSystem.Data.SqlClient;namespace_0033 {-
publicpartialclassForm1 : Form { -
publicForm1() { -
InitializeComponent(); -
} -
//заполняем данными из коллекции -
privatevoidbutton1_Click(objectsender, EventArgs e) { -
List<string> Array =newList<string> { -
"red", -
"green", -
"blue" -
}; -
foreach(stringiinArray) { -
checkedListBox1.Items.Add(i); -
} -
} -
//заполняем данными из текстового файла -
privatevoidbutton2_Click(objectsender, EventArgs e) { -
//путь -
stringpath =@"TextFile1.txt"; -
//если файл существует -
if(File.Exists(path)) { -
//создаем байтовый поток и привязываем его к файлу -
//в конструкторе указываем: путь кодировка -
using(StreamReader sr =newStreamReader(path, Encoding.UTF8)) { -
while(!sr.EndOfStream) { -
checkedListBox2.Items.Add(sr.ReadLine()); -
} -
} -
} -
else{ -
MessageBox.Show("Такой файл не существует!"); -
} -
} -
//заполняем данными из XML файла -
privatevoidbutton3_Click(objectsender, EventArgs e) { -
//путь -
stringpath =@"XMLFile1.xml"; -
//если файл существует -
if(File.Exists(path)) { -
XmlDocument XmlDoc =newXmlDocument(); -
//загружаем XML документ -
XmlDoc.Load(path); -
//получаем все дочерние элементы корневого элемента -
//xmlDoc.DocumentElement - корневой элемент -
foreach(XmlNode iinXmlDoc.DocumentElement.ChildNodes) { -
foreach(XmlNode jini.ChildNodes) { -
checkedListBox3.Items.Add(j.InnerText); -
} -
} -
} -
else{ -
MessageBox.Show("Такой файл не существует!"); -
} -
} -
//заполняем данными из базы данных -
privatevoidbutton4_Click(objectsender, EventArgs e) { -
//строка подключения к источнику данных -
stringconnectSting =@"Data Source=.\MSSQLSERVER2012;Initial Catalog=star;Integrated Security=True"; -
//sql запрос -
stringsql ="select Color from Colors"; -
//создаем подключение -
using(SqlConnection myConnection =newSqlConnection(connectSting)) { -
//применяем запрос к источнику данных -
SqlCommand myCommand =newSqlCommand(sql, myConnection); -
try{ -
//открываем соединение -
myConnection.Open(); -
//создаем объект для извлечения данных -
SqlDataReader myReader = myCommand.ExecuteReader(); -
//извлекаем данные -
while(myReader.Read()) { -
checkedListBox4.Items.Add(myReader[0]); -
} -
} -
catch(Exception ex) { -
MessageBox.Show(" Соединение не установлено!"); -
} -
} -
} -
} }