Compare commits

...

25 Commits

Author SHA1 Message Date
abb53f73a8 извините забыл какушку убрать 2024-12-13 02:44:59 +03:00
f04fe6fb49 сменил версию 2024-12-13 02:36:20 +03:00
c23ba3f723 Чутка переделал 2024-12-13 02:35:13 +03:00
2379a26a34 Добавил Clear 2024-12-11 20:18:46 +04:00
8c46c90cb9 fix 2024-12-11 16:04:21 +04:00
da0b0b3c97 чет подправила, у меня там очень много закомментированного кода было... 2024-11-05 18:50:01 +04:00
dd9e86a211 все работает НАКОНЕЦ ТО Я ЕГО РОТ НАОБОРОТ да и поздно уже... на паре ему не работалось...( 2024-10-23 22:51:01 +04:00
78cadc292f что-то работает во втором компоненте, но это все ТАКОЕ Г.... 2024-10-23 17:55:00 +04:00
db33928447 работает третий компонент, а второй не работает 2024-10-22 12:40:57 +04:00
e2e42acf98 так.. ну я начала что-то делать и устала. 6 часов делала второй компонент, гпт всякую фигню советует, опять переделывать... нужно настроить объединение ячеек в таблице и вообще вывод информации 2024-10-20 17:52:02 +04:00
c357d9e21b продолжаю делать 2 лабу... 2024-10-07 14:38:45 +04:00
4ef34fb579 изменения делаю во второй лабе, но я доделала и у меня приняли 1 лабу, 3 компонент 2024-10-07 14:15:47 +04:00
8a74c38488 начала делать второй компонент 2024-10-06 23:30:51 +04:00
877dcc8eed убрала излишние комментарии :/ для первого компонента 2024-10-06 22:26:24 +04:00
719ba80758 готов первый компонент 2024-10-06 22:24:58 +04:00
d79cf20111 рабочий третий компонент без символов начала и конца и спроверкой на нуллбл 2024-09-28 13:59:17 +04:00
d270df92c0 какие-то танцы с бубном по третьему компоненту и считыванию подстроки 2024-09-23 14:04:59 +04:00
da7b64ec6f чет проверила в лабе, подправила (в третьем компоненте...)
вроде работает
2024-09-23 01:06:36 +04:00
bbc5701cbc работает третий компонент :_) 2024-09-21 17:36:24 +04:00
0bd7fd69e3 второй компонент работает 2024-09-14 22:23:11 +04:00
89ceade732 в процессе разработки второго компонента 2024-09-06 22:21:18 +04:00
be6e8d0466 начинаю делать компонент ввода 2024-09-06 11:44:11 +04:00
33f373fde7 добавила тестовое приложение и протестировала компонент выбора из списка 2024-09-06 11:43:48 +04:00
8084f4f79a добавила компонент выбора из списка 2024-09-06 11:43:25 +04:00
34989eaa4a создание проекта 2024-09-06 10:02:55 +04:00
27 changed files with 2321 additions and 0 deletions

View File

@ -0,0 +1,92 @@
namespace TestAppForCheckComponentsWorking
{
partial class FormTestNoVisibleComponents
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
buttonSaveBigTextToWord = new Button();
bigTextWordNoVisibleComponent = new UserComponentsOption19.BigTextWordNoVisibleComponent(components);
tableWordNoVisibleComponent = new UserComponentsOption19.TableWordNoVisibleComponent(components);
buttonSaveTableToWord = new Button();
diagramWordNoVisibleComponent1 = new UserComponentsOption19.DiagramWordNoVisibleComponent(components);
buttonSaveDiagram = new Button();
SuspendLayout();
//
// buttonSaveBigTextToWord
//
buttonSaveBigTextToWord.Location = new Point(12, 21);
buttonSaveBigTextToWord.Name = "buttonSaveBigTextToWord";
buttonSaveBigTextToWord.Size = new Size(270, 29);
buttonSaveBigTextToWord.TabIndex = 0;
buttonSaveBigTextToWord.Text = "Сохранить большой текст в ворд :)";
buttonSaveBigTextToWord.UseVisualStyleBackColor = true;
buttonSaveBigTextToWord.Click += buttonSaveBigTextToWord_Click;
//
// buttonSaveTableToWord
//
buttonSaveTableToWord.Location = new Point(12, 81);
buttonSaveTableToWord.Name = "buttonSaveTableToWord";
buttonSaveTableToWord.Size = new Size(270, 29);
buttonSaveTableToWord.TabIndex = 1;
buttonSaveTableToWord.Text = "Сохранить таблицу в ворд :>";
buttonSaveTableToWord.UseVisualStyleBackColor = true;
buttonSaveTableToWord.Click += buttonSaveTableToWord_Click;
//
// buttonSaveDiagram
//
buttonSaveDiagram.Location = new Point(12, 142);
buttonSaveDiagram.Name = "buttonSaveDiagram";
buttonSaveDiagram.Size = new Size(270, 29);
buttonSaveDiagram.TabIndex = 2;
buttonSaveDiagram.Text = "Сохранить диаграмму в ворд :>";
buttonSaveDiagram.UseVisualStyleBackColor = true;
buttonSaveDiagram.Click += buttonSaveDiagram_Click;
//
// FormTestNoVisibleComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(433, 383);
Controls.Add(buttonSaveDiagram);
Controls.Add(buttonSaveTableToWord);
Controls.Add(buttonSaveBigTextToWord);
Name = "FormTestNoVisibleComponents";
Text = "FormTestNoVisibleComponents";
ResumeLayout(false);
}
#endregion
private Button buttonSaveBigTextToWord;
private UserComponentsOption19.BigTextWordNoVisibleComponent bigTextWordNoVisibleComponent;
private UserComponentsOption19.TableWordNoVisibleComponent tableWordNoVisibleComponent;
private Button buttonSaveTableToWord;
private UserComponentsOption19.DiagramWordNoVisibleComponent diagramWordNoVisibleComponent1;
private Button buttonSaveDiagram;
}
}

View File

@ -0,0 +1,154 @@
using UserComponentsOption19;
namespace TestAppForCheckComponentsWorking
{
public partial class FormTestNoVisibleComponents : Form
{
public FormTestNoVisibleComponents()
{
InitializeComponent();
}
private void buttonSaveBigTextToWord_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "ХОБА давай знакомиться! :D";
string[] data = { "Привет, я Саня", "НЕт... это я Саня..", "чЮваки... будьте спокойнее _~_" };
bigTextWordNoVisibleComponent.CreateAndSaveDocument(filePath, title, data);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
private void buttonSaveTableToWord_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
var dataList = new List<Employee>{
new Employee { Id = 1, Status = "нет", FirstName = "Иван", LastName = "Иванов", Age = 34, Children = "нет", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 },
new Employee { Id = 2, Status = "есть", FirstName = "Петр", LastName = "Петров", Age = 44, Children = "есть", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 },
new Employee { Id = 3, Status = "да", FirstName = "Сергей", LastName = "Сергеев", Age = 55, Children = "да", Car = "есть", Position = "Рук.", Departament = "Деп.", Bonus = 5000.5 },
new Employee { Id = 4, Status = "есть", FirstName = "Ольга", LastName = "Иванова", Age = 34, Children = "есть", Car = "нет", Position = "Бух.", Departament = "Бухг.", Bonus = 2000.1 },
new Employee { Id = 5, Status = "да", FirstName = "Татьяна", LastName = "Петрова", Age = 44, Children = "да", Car = "нет", Position = "Ст. бух.", Departament = "Бухг.", Bonus = 7000.6 }
};
string[] headerRow1 = { "Идент.", "Статус", "Личные данные", "Личные данные", "Личные данные", "Дети", "Машина", "Работа", "Работа", "Премия" };
string[] headerRow2 = { "Идент.", "Статус", "Имя", "Фамилия", "Возраст", "Дети", "Машина", "Должность", "Подразделение", "Премия" };
var headerTitles = new List<string[]>
{
new[] { "Идент.", "Статус", "Личные данные", "Личные данные", "Личные данные", "Дети", "Машина", "Работа", "Работа", "Премия" },
new[] { "Идент.", "Статус", "Имя", "Фамилия", "Возраст", "Дети", "Машина", "Должность", "Подразделение", "Премия" }
};
var columnWidths = new List<float> { 3.0f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 2.0f, 2.0f };
var columnMerges = new List<(int StartColumn, int EndColumn)>
{
(2, 4), // Объединяем "Личные данные" на три столбца
(7, 8) // Объединяем "Работа" на два столбца
};
var columnPropertyMapping = new Dictionary<int, string>
{
{ 0, "Id" },
{ 1, "Status" },
{ 2, "FirstName" },
{ 3, "LastName" },
{ 4, "Age" },
{ 5, "Children" },
{ 6, "Car" },
{ 7, "Position"},
{ 8, "Departament" },
{ 9, "Bonus" }
};
tableWordNoVisibleComponent.CreateTableInWordDocument(filePath, "Оп... какие-то рабы", columnMerges, columnWidths,
headerRow1, headerRow2, columnPropertyMapping, dataList);
//tableWordNoVisibleComponent.CreateWordTestTable(filePath);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
public class Employee
{
public int Id { get; set; }
public string Status { get; set; } = string.Empty;
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public int Age { get; set; }
public string Children { get; set; } = string.Empty;
public string Car { get; set; } = string.Empty;
public string Departament { get; set; } = string.Empty;
public string Position { get; set; } = string.Empty;
public double Bonus { get; set; }
}
private void buttonSaveDiagram_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "ХОБА давай знакомиться! :D";
var chartData = new List<DiagramWordNoVisibleComponent.ChartSeries>
{
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 1",
Data = new List<double> { 10, 5, 30, 4, 500 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 2",
Data = new List<double> { 15, 5, 25, 10, 1 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 3",
Data = new List<double> { 20, 30, 40, 50, 60 }
}
};
List<string> legend = new List<string>{"Понедельник","Вторник","Среда","Четверг","Пятница" };
diagramWordNoVisibleComponent1.CreateDocumentWithChart(filePath, title, "Diagram", DiagramWordNoVisibleComponent.LegendPosition.Bottom,
chartData, legend);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="bigTextWordNoVisibleComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="tableWordNoVisibleComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>300, 17</value>
</metadata>
<metadata name="diagramWordNoVisibleComponent1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>568, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,93 @@
namespace TestAppForCheckComponentsWorking
{
partial class FormTest
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
selectComponent = new UserComponentsOption19.SelectComponent();
writeComponent = new UserComponentsOption19.WriteComponent();
listComponent = new UserComponentsOption19.ListComponent();
button = new Button();
SuspendLayout();
//
// selectComponent
//
selectComponent.Location = new Point(12, 12);
selectComponent.Name = "selectComponent";
selectComponent.SelectedValue = "";
selectComponent.Size = new Size(189, 36);
selectComponent.TabIndex = 0;
//
// writeComponent
//
writeComponent.Location = new Point(12, 65);
writeComponent.Name = "writeComponent";
writeComponent.Size = new Size(324, 44);
writeComponent.TabIndex = 1;
writeComponent.Template = null;
//
// listComponent
//
listComponent.Location = new Point(16, 120);
listComponent.Name = "listComponent";
listComponent.SelectedIndex = -1;
listComponent.Size = new Size(406, 315);
listComponent.TabIndex = 2;
listComponent.ChangeSelectedItem += ChangeSelectedItem;
//
// button
//
button.Location = new Point(414, 65);
button.Name = "button";
button.Size = new Size(94, 29);
button.TabIndex = 3;
button.Text = "button1";
button.UseVisualStyleBackColor = true;
button.Click += button_Click;
//
// FormTest
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(635, 533);
Controls.Add(button);
Controls.Add(listComponent);
Controls.Add(writeComponent);
Controls.Add(selectComponent);
Name = "FormTest";
Text = "нукась протестируем...";
ResumeLayout(false);
}
#endregion
private UserComponentsOption19.SelectComponent selectComponent;
private UserComponentsOption19.WriteComponent writeComponent;
private UserComponentsOption19.ListComponent listComponent;
private Button button;
}
}

View File

@ -0,0 +1,111 @@
using System.Text.RegularExpressions;
using UserComponentsOption19;
namespace TestAppForCheckComponentsWorking
{
public partial class FormTest : Form
{
public List<string> testList = new List<string>();
Random rand = new Random();
public FormTest()
{
InitializeComponent();
FillList(19);
SetTemplate();
FillListBox();
}
private void SelectComponent_SelectComponentChanged(object? sender, EventArgs e)
{
MessageBox.Show("íó âûçâàë òû ìåíÿ, è ÷òî äàëüøå?");
}
private void FillList(int num)
{
for (int i = 0; i <= num; i++)
{
testList.Add("ß ñúåì " + i.ToString() + " àðáóçîâ!");
}
selectComponent.FillList(testList);
}
Regex regex = new Regex(@"^[^@\s]+@[^@\s]+\.(com|net|org|gov|ru)$");
public void SetTemplate()
{
writeComponent.Template = regex;
writeComponent.SetTextTooltip("email@email.ru");
try
{
//writeComponent.WriteTextInTextBox.ToString();
//writeComponent.WriteTextInTextBox = writeComponent.WriteTextInTextBox.ToString();
writeComponent.WriteTextInTextBox = "email@email.com";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button_Click(object sender, EventArgs e)
{
try
{
writeComponent.WriteTextInTextBox.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class Cat()
{
public int? Age { get; set; }
public string? Name { get; set; }
}
public void FillListBox()
{
try
{
listComponent.FillTemplateString("Êîò: (Name), âîçðàñò: (Age)", "(", ")");
for (int i = 0; i <= 10; i++)
{
Cat cat = new Cat();
cat.Name = "kitti" + i.ToString();
cat.Age = i;
listComponent.AddObjectToListBox(cat);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ChangeSelectedItem(object sender, EventArgs e)
{
var newCat = listComponent.GetObjectFromSelectedRow<Cat>();
if (newCat != null)
{
MessageBox.Show(newCat.Name);
MessageBox.Show(newCat.Age.ToString());
}
string placeHolder = "(Name)";
//listComponent.GetNameOfProperty("Êîò ñ èìåíåì (Name)", placeHolder);
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,17 @@
namespace TestAppForCheckComponentsWorking
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormTestNoVisibleComponents());
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\UserComponentsOption19\UserComponentsOption19.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34714.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UserComponentsOption19", "UserComponentsOption19\UserComponentsOption19.csproj", "{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAppForCheckComponentsWorking", "TestAppForCheckComponentsWorking\TestAppForCheckComponentsWorking.csproj", "{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Release|Any CPU.Build.0 = Release|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5466B454-D3BC-46EA-8960-7193721A5CF0}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class BigTextWordNoVisibleComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,61 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.ComponentModel;
// КОМПОНЕНТ С БОЛЬШИМ... ТЕКСТОМ
namespace UserComponentsOption19
{
public partial class BigTextWordNoVisibleComponent : Component
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
public BigTextWordNoVisibleComponent()
{
InitializeComponent();
}
public BigTextWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
public void CreateAndSaveDocument(string filePath, string title, string[] data)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath), "Укажите путь к файлу :_3");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title), "Заголовок документа не заполнен...");
}
if (data == null || data.Length == 0)
{
throw new ArgumentNullException(nameof(data), "Массив строк где, Алеша? >:/");
}
using (_wordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
var mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
var titleParagraph = new Paragraph(new Run(new Text(title)));
titleParagraph.ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center },
new Bold());
_docBody.AppendChild(titleParagraph);
_docBody.AppendChild(new Paragraph());
foreach (var paragraphText in data)
{
var paragraph = new Paragraph(new Run(new Text(paragraphText)));
_docBody.AppendChild(paragraph);
}
mainPart.Document.Save();
}
}
}
}

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class DiagramWordNoVisibleComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,328 @@
using System.ComponentModel;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
namespace UserComponentsOption19
{
public partial class DiagramWordNoVisibleComponent : Component
{
public DiagramWordNoVisibleComponent()
{
InitializeComponent();
}
public DiagramWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
// Перечисление для позиции легенды
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
// Класс для представления серии данных
public class ChartSeries
{
public string? Name { get; set; }
public List<double>? Data { get; set; }
}
// Основной метод для создания документа с диаграммой
public void CreateDocumentWithChart(string fileName, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData, List<string> legendData)
{
// Проверка входных данных
if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(documentTitle) || chartData == null || chartData.Count == 0 || chartData[0].Data.Count != legendData.Count)
{
throw new ArgumentException("Некорректные входные данные: проверьте имя файла, заголовок документа и наличие данных для диаграммы.");
}
// Создаем Word документ
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
wordApp.Visible = false; // Скрыть приложение Word
// Добавляем заголовок документа
var titleRange = document.Range();
titleRange.Text = documentTitle;
titleRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
titleRange.Font.Size = 14; // Размер шрифта для заголовка
titleRange.InsertParagraphAfter();
// Создаём Excel для диаграммы
var excelApp = new Excel.Application();
var workbook = excelApp.Workbooks.Add();
var worksheet = (Excel.Worksheet)workbook.Worksheets[1];
// Заполняем данные для диаграммы
int seriesCount = chartData.Count;
int dataCount = chartData[0].Data.Count;
for (int j = 0; j < dataCount; j++)
{
worksheet.Cells[1,j+2] = legendData[j]; // Заполнение заголовков
}
for (int i = 0; i < seriesCount; i++)
{
worksheet.Cells[i + 2, 1] = chartData[i].Name; // Заголовки серий
for (int j = 0; j < dataCount; j++)
{
worksheet.Cells[i+2,j+2] = chartData[i].Data[j]; // Заполнение данных
}
}
// Создание диаграммы
var chartObject = (Excel.ChartObject)worksheet.ChartObjects().Add(100, 100, 300, 200);
var chart = chartObject.Chart;
chart.SetSourceData(worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[seriesCount+1, dataCount + 1]]);
chart.ChartType = Excel.XlChartType.xlLine; // Линейная диаграмма
chart.HasTitle = true;
chart.ChartTitle.Text = chartTitle;
// Установка позиции легенды
switch (legendPosition)
{
case LegendPosition.Top:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;
break;
case LegendPosition.Bottom:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionBottom;
break;
case LegendPosition.Left:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionLeft;
break;
case LegendPosition.Right:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight;
break;
}
//// Экспорт диаграммы в PNG
//string chartPath = Path.Combine(Path.GetTempPath(), "chart.png");
//chart.Export(chartPath, "PNG", false);
// Теперь вставляем изображение в документ Word
//var paragraph = document.Content.Paragraphs.Add();
//paragraph.Range.InlineShapes.AddChart2(chart);
// Копирование диаграммы в буфер обмена
chartObject.Copy();
// Вставка диаграммы в документ Word
var range = document.Content;
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.Paste();
// Сохраняем документ
document.SaveAs2(fileName);
document.Close();
wordApp.Quit();
// Закрываем Excel
//workbook.SaveAs("C:\\Users\\pyata\\Documents\\excel.xlsx");
workbook.Close(false);
excelApp.Quit();
}
}
}
//using DocumentFormat.OpenXml.Drawing.Charts;
//using DocumentFormat.OpenXml.Drawing.Wordprocessing;
//using DocumentFormat.OpenXml.Packaging;
//using DocumentFormat.OpenXml;
//using System.ComponentModel;
//using DocumentFormat.OpenXml.Wordprocessing;
//using Index = DocumentFormat.OpenXml.Drawing.Charts.Index;
//using DocumentFormat.OpenXml.Drawing;
//DocumentFormat.OpenXml.Drawing.Charts.Index chartIndex = new DocumentFormat.OpenXml.Drawing.Charts.Index();
//namespace UserComponentsOption19
//{
// public partial class DiagramWordNoVisibleComponent : Component
// {
// public DiagramWordNoVisibleComponent()
// {
// InitializeComponent();
// }
// public DiagramWordNoVisibleComponent(IContainer container) : this()
// {
// container.Add(this);
// }
// // Перечисление для позиции легенды
// public enum LegendPosition
// {
// Top,
// Bottom,
// Left,
// Right
// }
// // Класс для представления серии данных
// public class ChartSeries
// {
// public string? Name { get; set; }
// public List<double>? Data { get; set; }
// }
// // Основной метод для создания документа с диаграммой
// public void CreateDocumentWithChart(string fileName, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData)
// {
// // Проверка входных данных
// if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(documentTitle) || chartData == null || chartData.Count == 0)
// {
// throw new ArgumentException("Некорректные входные данные: проверьте имя файла, заголовок документа и наличие данных для диаграммы.");
// }
// // Создаем Word документ
// using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
// {
// // Основная часть документа
// MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// mainPart.Document = new Document();
// Body body = new Body();
// // Добавляем заголовок документа
// DocumentFormat.OpenXml.Drawing.Paragraph titleParagraph = CreateTitle(documentTitle);
// body.AppendChild(titleParagraph);
// // Добавляем диаграмму в документ
// ChartPart chartPart = mainPart.AddNewPart<ChartPart>();
// GenerateChart(chartPart, chartTitle, legendPosition, chartData);
// // Вставляем диаграмму в документ
// Drawing chartDrawing = CreateChartDrawing(chartPart);
// DocumentFormat.OpenXml.Drawing.Paragraph chartParagraph = new DocumentFormat.OpenXml.Drawing.Paragraph(new DocumentFormat.OpenXml.Drawing.Run(chartDrawing));
// body.AppendChild(chartParagraph);
// mainPart.Document.Append(body);
// mainPart.Document.Save();
// }
// }
// // Метод для генерации заголовка документа
// private DocumentFormat.OpenXml.Drawing.Paragraph CreateTitle(string documentTitle)
// {
// var titleParagraph = new DocumentFormat.OpenXml.Drawing.Paragraph(new DocumentFormat.OpenXml.Drawing.Run(new DocumentFormat.OpenXml.Drawing.Text(documentTitle)));
// titleParagraph.ParagraphProperties = new DocumentFormat.OpenXml.Drawing.ParagraphProperties(new Justification { Val = JustificationValues.Center });
// return titleParagraph;
// }
// // Метод для создания диаграммы
// private void GenerateChart(ChartPart chartPart, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData)
// {
// ChartSpace chartSpace = new ChartSpace();
// DocumentFormat.OpenXml.Drawing.Charts.Chart chart = new DocumentFormat.OpenXml.Drawing.Charts.Chart();
// chart.Append(new Title(new ChartText(new RichText(new DocumentFormat.OpenXml.Drawing.Run(new DocumentFormat.OpenXml.Drawing.Text(chartTitle))))));
// PlotArea plotArea = new PlotArea();
// LineChart lineChart = new LineChart();
// uint index = 0;
// // Добавляем данные серий в диаграмму
// foreach (var series in chartData)
// {
// if (series.Name == null || series.Data == null || series.Data.Count == 0)
// {
// throw new ArgumentException("Некорректные данные серии.");
// }
// LineChartSeries lineChartSeries = new LineChartSeries(
// new Index { Val = index },
// new Order { Val = index },
// new SeriesText(new StringReference { Formula = new DocumentFormat.OpenXml.Drawing.Charts.Formula(series.Name) }));
// // Добавляем значения данных
// var numberLiteral = new NumberLiteral();
// numberLiteral.Append(new PointCount() { Val = (uint)series.Data.Count });
// foreach (var dataPoint in series.Data)
// {
// numberLiteral.Append(new NumericValue(dataPoint.ToString()));
// }
// lineChartSeries.Append(new DocumentFormat.OpenXml.Drawing.Charts.Values(numberLiteral));
// lineChart.Append(lineChartSeries);
// index++;
// }
// plotArea.Append(lineChart);
// chart.Append(plotArea);
// // Добавляем легенду
// Legend legend = CreateLegend(legendPosition);
// chart.Append(legend);
// chartSpace.Append(chart);
// chartPart.ChartSpace = chartSpace;
// }
// // Метод для создания легенды
// private Legend CreateLegend(LegendPosition legendPosition)
// {
// Legend legend = new Legend();
// LegendPositionValues legendPos;
// // Преобразуем наше перечисление в OpenXML значение
// switch (legendPosition)
// {
// case LegendPosition.Top:
// legendPos = LegendPositionValues.Top;
// break;
// case LegendPosition.Bottom:
// legendPos = LegendPositionValues.Bottom;
// break;
// case LegendPosition.Left:
// legendPos = LegendPositionValues.Left;
// break;
// case LegendPosition.Right:
// legendPos = LegendPositionValues.Right;
// break;
// default:
// throw new ArgumentOutOfRangeException(nameof(legendPosition), "Некорректная позиция легенды.");
// }
// legend.Append(new DocumentFormat.OpenXml.Drawing.Charts.LegendPosition()
// {
// Val = new EnumValue<LegendPositionValues>(legendPos)
// });
// return legend;
// }
// // Метод для вставки диаграммы в документ
// private Drawing CreateChartDrawing(ChartPart chartPart)
// {
// return new Drawing(
// new Inline(
// new Extent() { Cx = 5486400, Cy = 3200400 },
// new EffectExtent()
// {
// LeftEdge = 0L,
// TopEdge = 0L,
// RightEdge = 0L,
// BottomEdge = 0L
// },
// new DocProperties() { Id = (UInt32Value)1U, Name = "Chart 1" },
// new Graphic(
// new GraphicData(
// new ChartReference() { Id = chartPart.GetIdOfPart(chartPart) })
// { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })
// )
// { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U }
// );
// }
// }
//}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserComponentsOption19
{
internal class InvalidInputException : Exception
{
public InvalidInputException(string message) : base (message) { }
}
}

View File

@ -0,0 +1,62 @@
namespace UserComponentsOption19
{
partial class ListComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
listBox = new ListBox();
SuspendLayout();
//
// listBox
//
listBox.BackColor = Color.Honeydew;
listBox.Dock = DockStyle.Fill;
listBox.FormattingEnabled = true;
listBox.ItemHeight = 15;
listBox.Location = new Point(0, 0);
listBox.Margin = new Padding(3, 2, 3, 2);
listBox.Name = "listBox";
listBox.Size = new Size(763, 520);
listBox.TabIndex = 0;
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
//
// ListComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(listBox);
Margin = new Padding(3, 2, 3, 2);
Name = "ListComponent";
Size = new Size(763, 520);
ResumeLayout(false);
}
#endregion
private ListBox listBox;
}
}

View File

@ -0,0 +1,193 @@
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 UserComponentsOption19
{
public partial class ListComponent : UserControl
{
private string? _templateString;
private string? _startPropertyChar;
private string? _endPropertyChar;
public event EventHandler? ChangeSelectedItem;
public ListComponent()
{
InitializeComponent();
}
/// <summary>
/// публичный метод заполнения макетной строки
/// </summary>
/// <param name="templateString"></param>
/// <param name="startPropertyChar"></param>
/// <param name="endPropertyChar"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public void FillTemplateString(string templateString, string startPropertyChar, string endPropertyChar)
{
if (string.IsNullOrEmpty(templateString))
{
throw new ArgumentNullException("Введите макетную строку (не забудьте символы начала и конца свойства объекта :3)");
}
if (!templateString.Contains(startPropertyChar) || !templateString.Contains(endPropertyChar))
{
throw new InvalidOperationException("Вы не дописали символы начала и конца свойства объекта :_(");
}
_templateString = templateString;
_startPropertyChar = startPropertyChar;
_endPropertyChar = endPropertyChar;
}
/// <summary>
/// публичное свойство для получения/установки индекса строки
/// </summary>
public int SelectedIndex
{
get
{
if (listBox.SelectedIndex == -1) return -1;
return listBox.SelectedIndex;
}
set
{
if (listBox.SelectedIndex != -1)
{
listBox.SelectedIndex = value;
}
}
}
public T? GetObjectFromSelectedRow<T>() where T : class, new()
{
if (listBox.SelectedIndex == -1 || listBox.SelectedItem == null)
return null;
string? selectedString = listBox.SelectedItem.ToString();
T obj = new T();
Type objectType = typeof(T);
string selString = selectedString;
string tempString = _templateString;
List<string> arraySubstrings = new List<string>();
List<string> arrayPropertyNames = new List<string>();
List<string> Properties = new List<string>();
// заполняем массив сабстрингов
int index = 0;
int indexChar = 0;
for (int i = 0; i < tempString.Length; i++)
{
if (tempString[i] == _startPropertyChar[0])
{
indexChar = i;
arraySubstrings.Add(tempString.Substring(index, indexChar - index));
}
if (tempString[i] == _endPropertyChar[0])
{
index = i + 1;
}
}
// заполняем массив значений свойств
int d = 0;
for (int i = 0; i < arraySubstrings.Count; i++)
{
int startIndex = selString.IndexOf(arraySubstrings[i]) + arraySubstrings[i].Length - 1;
if (!(i + 1 >= arraySubstrings.Count))
{
int endIndex = selString.IndexOf(arraySubstrings[i + 1]);
string value = selString.Substring(startIndex, endIndex - startIndex);
Properties.Add(value);
d++;
}
}
if (d < arraySubstrings.Count)
{
int indexLastNameProperty = selString.IndexOf(arraySubstrings[arraySubstrings.Count - 1])
+ arraySubstrings[arraySubstrings.Count - 1].Length;
Properties.Add(selString.Substring(indexLastNameProperty, selString.Length - indexLastNameProperty));
}
// заполняем массив имен свойств
for (int i = 0; i < tempString.Length; i++)
{
if (tempString[i] == _startPropertyChar[0])
{
index = i + 1;
}
if (tempString[i] == _endPropertyChar[0])
{
indexChar = i;
arrayPropertyNames.Add(tempString.Substring(index, indexChar - index));
}
}
foreach (var property in objectType.GetProperties())
{
int propertyIndex = arrayPropertyNames.IndexOf(property.Name);
if (propertyIndex >= 0 && propertyIndex < Properties.Count)
{
Type propertyType = property.PropertyType;
Type? underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
object? converted = string.IsNullOrWhiteSpace(Properties[propertyIndex]) ? null : Convert.ChangeType(Properties[propertyIndex], underlyingType);
property.SetValue(obj, converted);
}
else
{
if(property.PropertyType == typeof(DateOnly))
{
if(obj is string)
{
property.SetValue(DateOnly.ParseExact(obj as string,"dd.mm.yyyy"), Convert.ChangeType(Properties[propertyIndex], property.PropertyType));
}
}
else
property.SetValue(obj, Convert.ChangeType(Properties[propertyIndex], property.PropertyType));
}
}
}
return obj;
}
public void AddObjectToListBox<T>(T? obj)
{
Type objectType = obj.GetType();
string result = _templateString;
foreach (var propertyInfo in objectType.GetProperties())
{
string placeholder = $"{_startPropertyChar}{propertyInfo.Name}{_endPropertyChar}";
var value = propertyInfo.GetValue(obj)?.ToString() ?? string.Empty;
result = result.Replace(placeholder, value);
}
listBox.Items.Add(result);
}
public void ClearRows()
{
listBox.Items.Clear();
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
ChangeSelectedItem?.Invoke(this, e);
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserComponentsOption19
{
internal class NoTemplateException : Exception
{
public NoTemplateException(string message) : base (message) { }
}
}

View File

@ -0,0 +1,58 @@
namespace UserComponentsOption19
{
partial class SelectComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
comboBox = new ComboBox();
SuspendLayout();
//
// comboBox
//
comboBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
comboBox.FormattingEnabled = true;
comboBox.Location = new Point(0, 0);
comboBox.Name = "comboBox";
comboBox.Size = new Size(151, 28);
comboBox.TabIndex = 0;
comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
//
// SelectComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(comboBox);
Name = "SelectComponent";
Size = new Size(151, 29);
ResumeLayout(false);
}
#endregion
private ComboBox comboBox;
}
}

View File

@ -0,0 +1,48 @@
namespace UserComponentsOption19
{
public partial class SelectComponent : UserControl
{
public event EventHandler? SelectComponentChanged;
Random rand = new Random();
public SelectComponent()
{
InitializeComponent();
//comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
}
public void FillList(List<string> list)
{
foreach (string item in list)
{
comboBox.Items.Add(item);
}
//comboBox.SelectedIndex = rand.Next(list.Count);
}
public void ClearList()
{
comboBox.Items.Clear();
}
public string SelectedValue
{
get
{
return comboBox.SelectedItem?.ToString() ?? string.Empty;
}
set
{
comboBox.SelectedItem = value;
}
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SelectComponentChanged?.Invoke(this, e);
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class TableWordNoVisibleComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,137 @@
using System.ComponentModel;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
/// КОМПОНЕНТ С ТАБЛИЦЕЙ ГДЕ ШАПКА - ЭТО ПЕРВЫЕ ДВЕ СТРОКИ
namespace UserComponentsOption19
{
public partial class TableWordNoVisibleComponent : Component
{
public TableWordNoVisibleComponent()
{
InitializeComponent();
}
public TableWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
public void CreateTableInWordDocument<T>(
string filePath,
string title,
List<(int start, int end)> mergeColumns,
List<float> columnWidths,
string[] headerRow1,
string[] headerRow2,
Dictionary<int, string> columnPropertyMapping,
List<T> data) where T : class
{
// Проверка входных данных
ValidateInput(filePath, title, mergeColumns, columnWidths, headerRow1, headerRow2, columnPropertyMapping, data);
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
// Установка заголовка
document.Content.Text = title;
// Добавление таблицы
var tableRange = document.Bookmarks["\\endofdoc"].Range;
Table table = document.Tables.Add(tableRange, data.Count + 2, headerRow1.Length);
table.Borders.Enable = 1;
// Заполнение данных
FillData(table, data, columnPropertyMapping, columnWidths);
// Заполнение заголовка
FillHeader(table, headerRow1, headerRow2, mergeColumns);
// Сохранение документа
document.SaveAs2(filePath);
document.Close();
wordApp.Quit();
}
private void ValidateInput<T>(
string filePath,
string title,
List<(int start, int end)> mergeColumns,
List<float> columnWidths,
string[] headerRow1,
string[] headerRow2,
Dictionary<int, string> columnPropertyMapping,
List<T> data)
{
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException("нужно ввести путь до файла");
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException("нужно ввести заголовок документа");
if (mergeColumns == null) throw new ArgumentNullException("где информация по объединению колонок?");
if (columnWidths == null) throw new ArgumentNullException("где информация по ширине колонок?");
if (headerRow1 == null || headerRow2 == null) throw new ArgumentNullException("нужно ввести заголовки");
if (data == null) throw new ArgumentNullException("все ввел, а данные забыл ввести? ну ты и умник");
if (columnPropertyMapping == null) throw new ArgumentNullException("все ввел, а данные забыл ввести? ну ты и умник");
}
private void FillHeader(Table table, string[] headerRow1, string[] headerRow2, List<(int start, int end)> mergeColumns)
{
for (int i = 0; i < headerRow2.Length; i++)
{
table.Cell(2, i + 1).Range.Text = headerRow2[i];
}
var sortDeskMergeColumns = mergeColumns.OrderByDescending(x => x.start);
List<int> notMergedColumns = new List<int>();
for (int i = 0; i < table.Columns.Count; i++)
{
notMergedColumns.Add(i);
}
for (int i = 0; i < table.Columns.Count; i++)
{
foreach (var item in mergeColumns)
{
if (i >= item.start && i <= item.end) notMergedColumns.Remove(i)
;
}
}
foreach (var item in notMergedColumns)
{
table.Cell(1, item + 1).Merge(table.Cell(2, item + 1));
table.Cell(1, item + 1).Range.Text = headerRow1[item];
}
foreach (var item in sortDeskMergeColumns)
{
table.Cell(1, item.start + 1).Merge(table.Cell(1, item.end + 1));
table.Cell(1, item.start + 1).Range.Text = headerRow1[item.start];
}
}
private void FillData<T>(Table table, List<T> data, Dictionary<int, string> columnPropertyMapping, List<float> columnWidths) where T : class
{
int rowIndex = 3;
foreach (var item in data)
{
for (int i = 0; i < columnPropertyMapping.Count; i++)
{
string propName = columnPropertyMapping[i];
var property = typeof(T).GetProperty(propName);
if (property != null)
{
var valueProp = property.GetValue(item)?.ToString() ?? string.Empty;
table.Cell(rowIndex, i + 1).Range.Text = valueProp;
}
else
{
table.Cell(rowIndex, i + 1).Range.Text = string.Empty;
}
}
rowIndex++;
}
}
}
}

View File

@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<VersionPrefix>1.0.6</VersionPrefix>
</PropertyGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Core">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>8</VersionMinor>
<VersionMajor>2</VersionMajor>
<Guid>2df8d04c-5bfa-101b-bde5-00aa0044de52</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Word">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>7</VersionMinor>
<VersionMajor>8</VersionMajor>
<Guid>00020905-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Excel">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>9</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>00020813-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,57 @@
namespace UserComponentsOption19
{
partial class WriteComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
textBox = new TextBox();
SuspendLayout();
//
// textBox
//
textBox.Location = new Point(3, 3);
textBox.Name = "textBox";
textBox.Size = new Size(310, 27);
textBox.TabIndex = 0;
textBox.TextChanged += textBox_TextChanged;
//
// WriteComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(textBox);
Name = "WriteComponent";
Size = new Size(320, 35);
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBox;
}
}

View File

@ -0,0 +1,74 @@
using System.Text.RegularExpressions;
namespace UserComponentsOption19
{
public partial class WriteComponent : UserControl
{
private Regex? regex;
private ToolTip toolTipTemplate = new ToolTip();
public event EventHandler? ChangeText;
public WriteComponent()
{
InitializeComponent();
}
public Regex? Template
{
get => regex;
set
{
regex = value;
}
}
public void SetTextTooltip(string toolTip)
{
toolTipTemplate.SetToolTip(textBox, toolTip);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
ChangeText?.Invoke(this, e);
}
public string WriteTextInTextBox
{
get
{
if (Template == null)
{
throw new NoTemplateException("Не установлен шаблон");
}
if (!Template.IsMatch(textBox.Text))
{
throw new InvalidInputException("Введенное значение не соответствует шаблону");
}
return textBox.Text;
}
set
{
if (Template != null)
{
if (Template.IsMatch(value))
{
textBox.Text = value;
}
else
{
throw new InvalidInputException("Введенное значение не соответствует шаблону");
}
}
else
{
textBox.Text = string.Empty;
}
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>