добавление данных
добавление и удаление данных программно
сортировка
связывание элемента управления с базой данных
заполняем элемент данными из разных источников данных
программно подогнать ширину элемента под текст
автоматическая прокрутка списка при добавлении элемента
добавление и удаление данных программно
сортировка
связывание элемента управления с базой данных
заполняем элемент данными из разных источников данных
программно подогнать ширину элемента под текст
автоматическая прокрутка списка при добавлении элемента
добавление данных
Добавить данные можно с помощью диалогового окна или конструктора формы.
Выберите свойство Items и нажмите на кнопку или раскройте треугольник в элементе и нажмите на Edit Items, появится диалоговое окно, где можно добавить данные.
Выберите свойство Items и нажмите на кнопку или раскройте треугольник в элементе и нажмите на Edit Items, появится диалоговое окно, где можно добавить данные.

Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApplication1 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApplication1 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
}
}

добавление и удаление данных программно
Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0042 {
-
public
partial
class
Form1 : Form {
-
//промежуточное свойство, которому будут передаваться данные из дочерней формы
-
public
ListBox Between {
-
set
{
-
listBox1.Items.Add(value);
-
}
-
get
{
-
return
listBox1;
-
}
-
}
-
public
Form1() {
-
InitializeComponent();
-
}
-
//кнопка Добавить
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
//открываем дочернюю форму и передаем ей ссылку
-
new
Form2().ShowDialog(
this
);
-
}
-
//кнопка Удалить
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Remove(listBox1.SelectedItem);
-
}
-
//кнопка Удалить все
-
private
void
button3_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Clear();
-
}
-
//кнопка OK
-
private
void
button4_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button5_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0042 {
-
public
partial
class
Form1 : Form {
-
//промежуточное свойство, которому будут передаваться данные из дочерней формы
-
public
ListBox Between {
-
set
{
-
listBox1.Items.Add(value);
-
}
-
get
{
-
return
listBox1;
-
}
-
}
-
public
Form1() {
-
InitializeComponent();
-
}
-
//кнопка Добавить
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
//открываем дочернюю форму и передаем ей ссылку
-
new
Form2().ShowDialog(
this
);
-
}
-
//кнопка Удалить
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Remove(listBox1.SelectedItem);
-
}
-
//кнопка Удалить все
-
private
void
button3_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Clear();
-
}
-
//кнопка OK
-
private
void
button4_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button5_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
}
-
}
}
Form2.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0042 {
-
public
partial
class
Form2 : Form {
-
public
Form2() {
-
InitializeComponent();
-
}
-
//кнопка OK
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
/*создаем переменную родительской формы (Form1)и присваиваем
-
ей значение через ссылку на родительскую форму*/
-
Form1 F1 = (Form1)
this
.Owner;
-
//присваиваем значение свойству в родительской форме
-
F1.Between.Items.Add(textBox1.Text);
-
//очищаем поле ввода
-
textBox1.Clear();
-
//передаем фокус
-
textBox1.Select();
-
}
-
//кнопка Close
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
this
.Close();
-
}
-
private
void
textBox1_KeyPress(
object
sender, KeyPressEventArgs e) {
-
if
(e.KeyChar == (
char
)Keys.Enter) {
-
//после нажатия клавиши Enter активируем кнопку OK
-
button1.Select();
-
//перехватываем нажатие клавиши, удаляем системный звук
-
e.Handled =
true
;
-
}
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0042 {
-
public
partial
class
Form2 : Form {
-
public
Form2() {
-
InitializeComponent();
-
}
-
//кнопка OK
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
/*создаем переменную родительской формы (Form1)и присваиваем
-
ей значение через ссылку на родительскую форму*/
-
Form1 F1 = (Form1)
this
.Owner;
-
//присваиваем значение свойству в родительской форме
-
F1.Between.Items.Add(textBox1.Text);
-
//очищаем поле ввода
-
textBox1.Clear();
-
//передаем фокус
-
textBox1.Select();
-
}
-
//кнопка Close
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
this
.Close();
-
}
-
private
void
textBox1_KeyPress(
object
sender, KeyPressEventArgs e) {
-
if
(e.KeyChar == (
char
)Keys.Enter) {
-
//после нажатия клавиши Enter активируем кнопку OK
-
button1.Select();
-
//перехватываем нажатие клавиши, удаляем системный звук
-
e.Handled =
true
;
-
}
-
}
-
}
}

сортировка
Если задать свойству Sorted значение true, данные будут отсортированы, а вот после того, как данные будут отсортированы, задать свойству Sorted значение false, то данные первоначальный несортированный вид, ПОЧЕМУ-ТО не принимают.
Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0043 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
//флажок
-
private
void
checkBox1_CheckedChanged(
object
sender, EventArgs e) {
-
listBox1.Sorted =
true
;
-
}
-
//кнопка ОК
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.SelectedItem +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0043 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
//флажок
-
private
void
checkBox1_CheckedChanged(
object
sender, EventArgs e) {
-
listBox1.Sorted =
true
;
-
}
-
//кнопка ОК
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
textBox1.Text +=
" "
+ listBox1.SelectedItem +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
}
-
}
}

связывание элемента управления с базой данных
На элементе управления раскройте треугольник.

Выберите флажок Use Data Bound Items.

Раскройте поле с выпадающим списком Data Source.

Добавьте источник данных. Кликните на Add Project Data Source. Выберите Database.

Выберите DataSet.

Выберите соединение.

Запомните имя соединения, если хотите, можете его изменить.

Выберите таблицы.

После того, как Visual Studio успешно создало соединение с базой данных, опять раскройте поле с выпадающим спискомData Source. Раскройте Other Data Sources. Раскройте starDataSet и выберите таблицу Colors.

Раскройте поле с выпадающим списком Display Member и выберите столбец Color. Данные этого столбца будут отображаться в списке. Данные этого столбца можно вывести с помощью свойства SelectedItem.

Если Вам нужно, то раскройте поле с выпадающим списком Value Member и выберите столбец id. Данные этого столбца можно вывести с помощью свойства SelectedValue.

Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0044 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
Form1_Load(
object
sender, EventArgs e) {
-
// TODO: This line of code loads data into the 'starDataSet.Colors' table. You can move, or remove it, as needed.
-
this
.colorsTableAdapter.Fill(
this
.starDataSet.Colors);
-
}
-
//кнопка OK
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
//ВНИМАНИЕ!!! при работе с базой данных, использование
-
//SelectedItem приводит к выводу не выбранного элемента, а
-
//System.Data.DataRowView
-
textBox1.Text +=
" "
+ listBox1.SelectedItem +
"\r\n"
;
-
textBox2.Text +=
" "
+ listBox1.SelectedValue +
"\r\n"
;
-
textBox3.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
textBox2.Clear();
-
textBox3.Clear();
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0044 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
Form1_Load(
object
sender, EventArgs e) {
-
// TODO: This line of code loads data into the 'starDataSet.Colors' table. You can move, or remove it, as needed.
-
this
.colorsTableAdapter.Fill(
this
.starDataSet.Colors);
-
}
-
//кнопка OK
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
//ВНИМАНИЕ!!! при работе с базой данных, использование
-
//SelectedItem приводит к выводу не выбранного элемента, а
-
//System.Data.DataRowView
-
textBox1.Text +=
" "
+ listBox1.SelectedItem +
"\r\n"
;
-
textBox2.Text +=
" "
+ listBox1.SelectedValue +
"\r\n"
;
-
textBox3.Text +=
" "
+ listBox1.Text +
"\r\n"
;
-
}
-
//кнопка Clear
-
private
void
button2_Click(
object
sender, EventArgs e) {
-
textBox1.Clear();
-
textBox2.Clear();
-
textBox3.Clear();
-
}
-
}
}

заполняем элемент данными из разных источников данных
В данном примере, наш элемент будет заполнен данными из: коллекции, текстового документа, XML файла, базы данных.
Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
//подключить пространство имен
using
System.IO;
//подключить пространство имен для кодировки
using
System.Text;
//подключить пространство имен
using
System.Xml;
//подключить пространство имен
using
System.Data.SqlClient;
namespace
_0045 {
-
public
partial
class
Form1 : Form {
-
List<
string
> Array =
new
List<
string
> {
-
"red"
,
-
"green"
,
-
"blue"
-
};
-
public
Form1() {
-
InitializeComponent();
-
//заполняем данными из коллекции
-
foreach
(
string
i
in
Array) {
-
listBox1.Items.Add(i);
-
}
-
//заполняем данными из текстового файла
-
//путь
-
string
pathTxt =
@"a.txt"
;
-
//если файл существует
-
if
(File.Exists(pathTxt)) {
-
//создаем байтовый поток и привязываем его к файлу
-
//в конструкторе указываем: путь кодировка
-
using
(StreamReader sr =
new
StreamReader(pathTxt, Encoding.UTF8)) {
-
while
(!sr.EndOfStream) {
-
listBox2.Items.Add(sr.ReadLine());
-
}
-
}
-
}
-
//заполняем данными из XML файла
-
//путь
-
string
pathXml =
@"a.xml"
;
-
//если файл существует
-
if
(File.Exists(pathXml)) {
-
XmlDocument XmlDoc =
new
XmlDocument();
-
//загружаем XML документ
-
XmlDoc.Load(pathXml);
-
//получаем все дочерние элементы корневого элемента
-
//xmlDoc.DocumentElement - корневой элемент
-
foreach
(XmlNode i
in
XmlDoc.DocumentElement.ChildNodes) {
-
foreach
(XmlNode j
in
i.ChildNodes) {
-
listBox3.Items.Add(j.InnerText);
-
}
-
}
-
}
-
//заполняем данными из базы данных
-
//строка подключения к источнику данных
-
string
connectSting =
@"Data Source=.\MSSQLSERVER2012;Initial Catalog=star;Integrated Security=True"
;
-
//sql запрос
-
string
sql =
"select Color from Colors"
;
-
//создаем подключение
-
using
(SqlConnection myConnection =
new
SqlConnection(connectSting)) {
-
//применяем запрос к источнику данных
-
SqlCommand myCommand =
new
SqlCommand(sql, myConnection);
-
try
{
-
//открываем соединение
-
myConnection.Open();
-
//создаем объект для извлечения данных
-
SqlDataReader myReader = myCommand.ExecuteReader();
-
//извлекаем данные
-
while
(myReader.Read()) {
-
listBox4.Items.Add(myReader[0]);
-
}
-
}
-
catch
(Exception ex) {
-
MessageBox.Show(
" Соединение не установлено!"
);
-
}
-
}
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
//подключить пространство имен
using
System.IO;
//подключить пространство имен для кодировки
using
System.Text;
//подключить пространство имен
using
System.Xml;
//подключить пространство имен
using
System.Data.SqlClient;
namespace
_0045 {
-
public
partial
class
Form1 : Form {
-
List<
string
> Array =
new
List<
string
> {
-
"red"
,
-
"green"
,
-
"blue"
-
};
-
public
Form1() {
-
InitializeComponent();
-
//заполняем данными из коллекции
-
foreach
(
string
i
in
Array) {
-
listBox1.Items.Add(i);
-
}
-
//заполняем данными из текстового файла
-
//путь
-
string
pathTxt =
@"a.txt"
;
-
//если файл существует
-
if
(File.Exists(pathTxt)) {
-
//создаем байтовый поток и привязываем его к файлу
-
//в конструкторе указываем: путь кодировка
-
using
(StreamReader sr =
new
StreamReader(pathTxt, Encoding.UTF8)) {
-
while
(!sr.EndOfStream) {
-
listBox2.Items.Add(sr.ReadLine());
-
}
-
}
-
}
-
//заполняем данными из XML файла
-
//путь
-
string
pathXml =
@"a.xml"
;
-
//если файл существует
-
if
(File.Exists(pathXml)) {
-
XmlDocument XmlDoc =
new
XmlDocument();
-
//загружаем XML документ
-
XmlDoc.Load(pathXml);
-
//получаем все дочерние элементы корневого элемента
-
//xmlDoc.DocumentElement - корневой элемент
-
foreach
(XmlNode i
in
XmlDoc.DocumentElement.ChildNodes) {
-
foreach
(XmlNode j
in
i.ChildNodes) {
-
listBox3.Items.Add(j.InnerText);
-
}
-
}
-
}
-
//заполняем данными из базы данных
-
//строка подключения к источнику данных
-
string
connectSting =
@"Data Source=.\MSSQLSERVER2012;Initial Catalog=star;Integrated Security=True"
;
-
//sql запрос
-
string
sql =
"select Color from Colors"
;
-
//создаем подключение
-
using
(SqlConnection myConnection =
new
SqlConnection(connectSting)) {
-
//применяем запрос к источнику данных
-
SqlCommand myCommand =
new
SqlCommand(sql, myConnection);
-
try
{
-
//открываем соединение
-
myConnection.Open();
-
//создаем объект для извлечения данных
-
SqlDataReader myReader = myCommand.ExecuteReader();
-
//извлекаем данные
-
while
(myReader.Read()) {
-
listBox4.Items.Add(myReader[0]);
-
}
-
}
-
catch
(Exception ex) {
-
MessageBox.Show(
" Соединение не установлено!"
);
-
}
-
}
-
}
-
}
}

программно подогнать ширину элемента под текст
Main.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApplication1 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
Graphics G = listBox1.CreateGraphics();
-
float
maxWidth = 0;
-
foreach
(
object
obj
in
listBox1.Items) {
-
float
w = G.MeasureString(obj.ToString(), listBox1.Font).Width;
-
if
(w > maxWidth) {
-
maxWidth = w;
-
}
-
}
-
G.Dispose();
-
listBox1.Width = (
int
)maxWidth;
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApplication1 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
Graphics G = listBox1.CreateGraphics();
-
float
maxWidth = 0;
-
foreach
(
object
obj
in
listBox1.Items) {
-
float
w = G.MeasureString(obj.ToString(), listBox1.Font).Width;
-
if
(w > maxWidth) {
-
maxWidth = w;
-
}
-
}
-
G.Dispose();
-
listBox1.Width = (
int
)maxWidth;
-
}
-
}
}

автоматическая прокрутка списка при добавлении элемента
При добавлении в список нового элемента, список автоматически прокручивается до этого самого элемента, что бы он был виден.
Form1.cs
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0046 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Add(textBox1.Text);
-
listBox1.TopIndex = listBox1.Items.Count - 1;
-
}
-
}
}
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
_0046 {
-
public
partial
class
Form1 : Form {
-
public
Form1() {
-
InitializeComponent();
-
}
-
private
void
button1_Click(
object
sender, EventArgs e) {
-
listBox1.Items.Add(textBox1.Text);
-
listBox1.TopIndex = listBox1.Items.Count - 1;
-
}
-
}
}
