Разработка приложений по работе с датой и системным временем. 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Разработка приложений по работе с датой и системным временем.



Вариант 7

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 WindowsFormsApplication7

{

public partial class Form1: Form

{

   public Form1()

   {

       InitializeComponent();

       timer1_Tick(timer1,new EventArgs());

   }

 

   private void timer1_Tick(object sender, EventArgs e)

   {

       DateTime d;

       d = DateTime.Now;

       label1.Text = d.ToLongDateString();

       label2.Text = d.ToLongTimeString();

   }

 

   private void button1_Click(object sender, EventArgs e)

   {

       DateTime d_Now, d_User;

       d_Now = DateTime.Now;

       // сегодняшняя дата

       d_User = Convert.ToDateTime(maskedTextBox1.Text); // ввод даты рождения

       if (d_Now < d_User)

           label3.Text = "Вы ещё не родились. Введите дату правильно!";

       else

       {

           int year = (d_Now.Year - d_User.Year);

           int m = d_Now.Month - d_User.Month;

           int d = d_Now.Day - d_User.Day;

           if (m < 0)

               year--;

           if (d < 0 && m==0)

               year--;

 

           string godi = " лет";

           if (year%10 == 1)

               godi = " год";

           if (year % 10 >= 2 && year % 10 <= 4)

               godi = " года";

           label3.Text ="Тебе уже "+ (year).ToString() + godi;

       }

   }

}

}


 

Работа с реестром ОС Windows

Вариант 7

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 WindowsFormsApplication8

{

public partial class Form1: Form

{

   public Form1()

   {

       InitializeComponent();

   }

 

   public bool tuda;

   int sec = 0;

   int w = 80, h = 80;

   int x = 1, y =20;

   int dx = 5;

 

   enum STATUS { Left, Right, Up, Down}; //направления движения

   STATUS flag;         //флаг изменения направления движения

   SolidBrush brush0 = new SolidBrush(Color.Red); // кисть

   SolidBrush brush1 = new SolidBrush(Color.Blue); // кисть

   Rectangle rc; //прямоугольная область, в которой находиться фигура

 

   // событие работы таймера с заданным интервалом

   private void timer1_Tick(object sender, EventArgs e)

   {

       sec++; // секунды

       rc = new Rectangle(x, y, w, h); // размер прямоугольной области

       this.Invalidate(rc, true); // вызываем прорисовку области

 

       if (w < 200)

       {

           if (flag == STATUS.Left)

               x -= dx;

           if (flag == STATUS.Right)

               x += dx;

           if (flag == STATUS.Up)

               y -= dx;

           if (flag == STATUS.Down)

               y += dx;

 

           if (x >= (this.ClientSize.Width - w)) // если достигли правого края формы

           {

               flag = STATUS.Left; // меняем статус движения на левый

               h++;

               w++;

           }

           else if (x <= 1) // если достигли левого края формы

           {

               flag = STATUS.Right; // меняем статус движения на правый

               h++;

               w++;

           }

 

           if (y >= (this.ClientSize.Height - w)) // если достигли края формы

           {

               flag = STATUS.Up; // меняем статус движения

               h++;

               w++;

           }

           else if (y <= 1) // если достигли края формы

           {

               flag = STATUS.Down; // меняем статус движения

               h++;

               w++;

           }

 

           rc = new Rectangle(x, y, w, h); // новая прямоугольная область

           this.Invalidate(rc, true); // вызываем прорисовку этой области

       }

   }

 

   private void Form1_Paint(object sender, PaintEventArgs e) // событие перерисовки формы

   {

       if (flag == STATUS.Left || flag == STATUS.Up)

           e.Graphics.FillEllipse(brush0, rc); // рисуем закрашенный эллипс

       else

           e.Graphics.FillEllipse(brush1, rc);

   }

 

   public int MySpeed

   {

       get

       {

           return 110 - timer1.Interval;

       }

       set

       {

           timer1.Interval = 110 - value;

       }

   }

 

   public Color MyColor0

   {

       get

       {

           return brush0.Color;

       }

       set

       {

           brush0.Color = value;

       }

   }

 

   private void button2_Click(object sender, EventArgs e)

   {

       w = 80;

       h = 80;

   }

 

   public Color MyColor1

   {

       get

       {

           return brush1.Color;

       }

       set

       {

           brush1.Color = value;

       }

   }

 

   private void button1_Click(object sender, EventArgs e)

   {

       Form2 f2 = new Form2();

       f2.Owner = this;

       f2.Show(this);

   }

    public void Rez(bool a)

   {

       if (a)

       {

           if (flag ==STATUS.Right)

               flag = STATUS.Left;

           else

               flag = STATUS.Right;

       }

       else

       {

           if (flag == STATUS.Up)

               flag = STATUS.Down;

           else

               flag = STATUS.Up;

       }

   }

}

}

 

using System;

using Microsoft.Win32;

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 WindowsFormsApplication8

{

public partial class Form2: Form

{

   public Form2()

   {

       InitializeComponent();

   }

       

   private void button1_Click(object sender, EventArgs e)

   {

       this.Hide();

   }

 

   private void trackBar1_Scroll(object sender, EventArgs e)

   {

       Form1 f1 = Owner as Form1;

       f1.MySpeed = trackBar1.Value * 10;

   }

 

   private void button2_Click(object sender, EventArgs e)

   {

       Form1 f1 = Owner as Form1;

       if (colorDialog1.ShowDialog() == DialogResult.OK)

           f1.MyColor0 = colorDialog1.Color;

   }

 

   private void button3_Click(object sender, EventArgs e)

   {

       Form1 f1 = Owner as Form1;

       if (colorDialog2.ShowDialog() == DialogResult.OK)

           f1.MyColor1 = colorDialog2.Color;

   }

 

   private void radioButton1_CheckedChanged(object sender, EventArgs e)

   {

       Form1 f1 = Owner as Form1;

       f1.Rez(true);

   }

 

   private void radioButton2_CheckedChanged(object sender, EventArgs e)

   {

       Form1 f1 = Owner as Form1;

       f1.Rez(false);

   }

   public void Save(Color cl0, Color cl1, byte by, bool tr)

   {

       RegistryKey currentUserKey = Registry.CurrentUser;

       RegistryKey Key = currentUserKey.CreateSubKey("FreeKey");

       int r = cl0.R;

       int g = cl0.G;

       int b = cl0.B;

       int r1 = cl1.R;

       int g1 = cl1.G;

       int b1 = cl1.B;

       Key.SetValue("tr", tr);

       Key.SetValue("r0", r);

       Key.SetValue("g0", g);

       Key.SetValue("b0", b);

       Key.SetValue("r1", r1);

       Key.SetValue("g1", g1);

       Key.SetValue("b1", b1);

       Key.SetValue("Speed", by);

       Key.Close();

   }

 

   private void button4_Click(object sender, EventArgs e)

   {

       Save(colorDialog1.Color,colorDialog2.Color,Convert.ToByte(trackBar1.Value),radioButton1.Checked);

   }

 

   private void button5_Click(object sender, EventArgs e)

   {

       RegistryKey currentUserKey = Registry.CurrentUser;

       RegistryKey Key = currentUserKey.OpenSubKey("FreeKey");

       trackBar1.Value = Convert.ToInt32(Key.GetValue("Speed"));

       bool tr = Convert.ToBoolean(Key.GetValue("tr"));

       int r = Convert.ToInt32(Key.GetValue("r0"));

       int g = Convert.ToInt32(Key.GetValue("g0"));

       int b = Convert.ToInt32(Key.GetValue("b0"));

       int r1 = Convert.ToInt32(Key.GetValue("r1"));

       int g1 = Convert.ToInt32(Key.GetValue("g1"));

       int b1 = Convert.ToInt32(Key.GetValue("b1"));

       Key.Close();

       Form1 f1 = Owner as Form1;

       if (tr)

           radioButton1.Checked = true;

       else

           radioButton2.Checked = true;

       colorDialog1.Color = Color.FromArgb(r,g,b);

       f1.MyColor0 = colorDialog1.Color;

       colorDialog2.Color = Color.FromArgb(r1, g1, b1);

       f1.MyColor1 = colorDialog2.Color;

   }

}

}


 

Шифрование данных


Вариант 7

 

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 WindowsFormsApplication9

{

public partial class Form1: Form

{

   const string SharedSecret = "rath/Haste. Grace or Discipline for survivability. Grace if with a group of ES users, Discipline if solo. HatrJ*()!G*Hjkasgasikg891gjh";

   public Form1()

   {

       InitializeComponent();

       openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       openFileDialog2.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       saveFileDialog2.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       saveFileDialog3.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

   }

 

   private void button1_Click(object sender, EventArgs e)

   {

      if (openFileDialog1.ShowDialog() == DialogResult.Cancel)

           return;

       Slovar.fn = openFileDialog1.FileName;

       Slovar.File_To_List();

       load();

   }

 

   private void button2_Click(object sender, EventArgs e)

   {

       if (Slovar.Poisk(textBox1.Text)!= -1)

           MessageBox.Show("Найдено в строке: " + Slovar.Poisk(textBox1.Text).ToString(), "Поиск", MessageBoxButtons.OK);

       else

           MessageBox.Show("Не найдено.", "Не найдено", MessageBoxButtons.OK, MessageBoxIcon.Error);

   }

 

   private void button3_Click(object sender, EventArgs e)

   {

       if (Slovar.Poisk(textBox1.Text)!= -1)

           MessageBox.Show("Удалено в строке:" + Slovar.Ydoli(textBox1.Text).ToString(), "Del", MessageBoxButtons.OK);

       else

           MessageBox.Show("Не найдено.", "Не найдено", MessageBoxButtons.OK, MessageBoxIcon.Error);

       load();

   }

   public void load()

     {

       Slovar.list.Sort();

       textBox2.Text = "";

       for (int i = 0; i < Slovar.list.Count; i++)

           if (Slovar.list[i]!= "")

               if (i < Slovar.list.Count-1)

                   textBox2.Text += Slovar.list[i] + Environment.NewLine;

               else textBox2.Text += Slovar.list[i];

   }

 

   private void button4_Click(object sender, EventArgs e)

   {

       if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)

           return;

       string filename = saveFileDialog1.FileName;

       System.IO.File.WriteAllText(filename, textBox2.Text);

       MessageBox.Show("Файл сохранен");

   }

 

   private void button5_Click(object sender, EventArgs e)

   {

       if (Slovar.Poisk(textBox1.Text) == -1)

       {

           Slovar.Dobavka(textBox1.Text);

           MessageBox.Show("Добавлено!", ":D", MessageBoxButtons.OK);

       }

       else

           MessageBox.Show("Уже существует!", "Повтор", MessageBoxButtons.OK, MessageBoxIcon.Error);

       load();

   }

 

   private void button6_Click(object sender, EventArgs e)

   {

       if (Slovar.PoiskPoSlogam(textBox1.Text)!= "")

           textBox3.Text = Slovar.PoiskPoSlogam(textBox1.Text);

       else

           MessageBox.Show("Не найдено.", "Не найдено", MessageBoxButtons.OK, MessageBoxIcon.Error);

   }

 

   private void button7_Click(object sender, EventArgs e)

   {

       if (saveFileDialog2.ShowDialog() == DialogResult.Cancel)

           return;

       string filename = saveFileDialog2.FileName;

       System.IO.File.WriteAllText(filename, textBox3.Text);

       MessageBox.Show("Файл сохранен");

   }

 

   private void button8_Click(object sender, EventArgs e)

   {

       var encryptedStringAES = Crypto.EncryptStringAES(textBox2.Text, SharedSecret);

       if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)

           return;

       string filename = saveFileDialog1.FileName;

       System.IO.File.WriteAllText(filename, encryptedStringAES);

       MessageBox.Show("Файл зашифрован");

   }

 

   private void button9_Click(object sender, EventArgs e)

   {

       if (openFileDialog2.ShowDialog() == DialogResult.Cancel)

           return;

       string netxt = System.IO.File.ReadAllText(openFileDialog2.FileName);

       textBox2.Text = Crypto.DecryptStringAES(netxt, SharedSecret);

       Slovar.list = new List<string>(textBox2.Lines);

       load();

   }

}

 

class Slovar

{

   static public string fn = "Словарь.txt";

   static public List<string> list = new List<string>();

 

   static public bool File_To_List() // загрузить файл в список

   {

       list.Clear();

       try

       {

           System.IO.StreamReader f = new System.IO.StreamReader(fn);

           while (!f.EndOfStream)

           {

               list.Add(f.ReadLine());

           }

           f.Close();

           return true;

       }

       catch

       {

           MessageBox.Show("Ошибка доступа к файлу!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

           return false;

       }

   }

 

   static public int Ydoli(string slovo)

   {

       for (int i = 0; i < list.Count; i++)

       {

           if (list[i] == slovo && slovo!= "")

           {

               list[i] = "";

               return i;

           }

       }

       return -1;

   }

 

   static public void Dobavka(string slovo)

   {

       list.Add(slovo);

   }

 

   static public int Poisk(string slovo)

   {

       for (int i = 0; i < list.Count; i++)

       {

           if (list[i] == slovo && slovo!= "")

           {

               return i;

           }

       }

       return -1;

   }

   static public string PoiskPoSlogam(string slovo)

   {

       string otv = "";

       for (int i = 0; i < list.Count; i++)

       {

           for(int s = 0,q=0; s < slovo.Length; s++){

               if ((list[i].Length >=slovo.Length) && ((list[i])[s] == slovo[s]) && (slovo!= ""))

               {

                   ++q;

                   if (q == slovo.Length)

                       otv += list[i] + Environment.NewLine;

               }

           }

       }

       return otv;

   }

}

}

 

 

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

 

namespace WindowsFormsApplication9

{

class Crypto

{

   private static readonly byte[] Salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

 

   /// <summary>

   /// Зашифровывает данную строку, используя AES. Строка может быть расшифрована с помощью

   /// DecryptStringAES(). Параметр sharedSecret должны совпадать.

   /// </summary>

   /// <param name="plainText">Текст для шифрования.</param>

   /// <param name="sharedSecret">Пароль, используемый для генерации ключа для шифрования.</param>

   public static string EncryptStringAES(string plainText, string sharedSecret)

   {

       if (string.IsNullOrEmpty(plainText))

           throw new ArgumentNullException("plainText");

       if (string.IsNullOrEmpty(sharedSecret))

           throw new ArgumentNullException("sharedSecret");

 

       string outStr;                  // Зашифрованная строка для return

       RijndaelManaged aesAlg = null;         // Объект RijndaelManaged используется для шифрования данных.

 

       try

       {

           // Генерация ключ из sharedSecret и Salt.

           var key = new Rfc2898DeriveBytes(sharedSecret, Salt);

 

           // Создание объекта RijndaelManaged

           aesAlg = new RijndaelManaged();

           aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

 

           // Создание расшифровщика для преобразования потока.

           ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

 

           // Создание потоков, используемых для шифрования.

           using (var msEncrypt = new MemoryStream())

           {

               // подготовка IV

               msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));

               msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);

               using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

               {

                   using (var swEncrypt = new StreamWriter(csEncrypt))

                   {

                       //Запись всех данных в поток.

                       swEncrypt.Write(plainText);

                   }

               }

               outStr = Convert.ToBase64String(msEncrypt.ToArray());

           }

       }

       finally

       {

           // Очистка RijndaelManaged.

           if (aesAlg!= null)

               aesAlg.Clear();

       }

 

       // Возвращает зашифрованные байты из потока.

       return outStr;

   }

 

   /// <summary>

   /// Расшифровывает данную строку. Предполагается, что строка была зашифрована с использованием

   /// EncryptStringAES(), используя идентичный sharedSecret.

   /// </summary>

   /// <param name="cipherText">Текст для расшифровки.</param>

   /// <param name="sharedSecret">Пароль, используемый для генерации ключа расшифровки.</param>

   public static string DecryptStringAES(string cipherText, string sharedSecret)

   {

       if (string.IsNullOrEmpty(cipherText))

           throw new ArgumentNullException("cipherText");

       if (string.IsNullOrEmpty(sharedSecret))

           throw new ArgumentNullException("sharedSecret");

 

       // Объявление объекта RijndaelManaged

       // используемого для расшифровки данных.

       RijndaelManaged aesAlg = null;

 

       // Объявление строки, используемой для хранения

       // расшифрованного текста.

       string plaintext;

 

       try

       {

           // генерирует ключ из sharedSecret и Salt

           var key = new Rfc2898DeriveBytes(sharedSecret, Salt);

 

           // Создание потоков, используемых для расшифровки.               

           byte[] bytes = Convert.FromBase64String(cipherText);

           using (var msDecrypt = new MemoryStream(bytes))

           {

               // Создание объекта RijndaelManaged

               // с указанным ключом и IV.

               aesAlg = new RijndaelManaged();

               aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

               // Получение вектора инициализации из зашифрованного потока

               aesAlg.IV = ReadByteArray(msDecrypt);

               // Создание дешифратора для выполнения потокового преобразования.

               ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

               using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

               {

                   using (var srDecrypt = new StreamReader(csDecrypt))

                       // Чтение дешифрованных байтов из потока дешифрования

                       // и помещение их в строку.

                       plaintext = srDecrypt.ReadToEnd();

               }

           }

       }

       finally

       {

           // Очистка RijndaelManaged.

           if (aesAlg!= null)

               aesAlg.Clear();

       }

       return plaintext;

   }

 

   private static byte[] ReadByteArray(Stream s)

   {

       var rawLength = new byte[sizeof(int)];

       if (s.Read(rawLength, 0, rawLength.Length) == rawLength.Length)

       {

           var buffer = new byte[BitConverter.ToInt32(rawLength, 0)];

           if (s.Read(buffer, 0, buffer.Length)!= buffer.Length)

           {

               throw new SystemException("Не правильно прочитан byte массив");

           }

           return buffer;

       }

       throw new SystemException("Поток не содержит правильно отформатированный byte массив");

   }

}

}


 

Тестирование приложения

 

using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using WindowsFormsApplication10;

 

namespace UnitTestProject1

{

[TestClass]

public class UnitTest1

{

   [TestMethod]

   public void Fail()

   {

       Form1 f = new Form1();

       int[] n = new int[5];

       string[] a = new string[5];

       a[0] = "Россия";

       for (int i = 0; i < a.Length; i++)

           n[i] = i * 2+1;

       f.Zapis(a, n);

   }

   [TestMethod]

   public void Yspeh()

   {

       Form1 f = new Form1();

       int[] n = new int[5];

       string[] a = new string[5];

       a[0] = "Россия";

       a[1] = "Великобритания";

       a[2] = "Украина";

       a[3] = "Польша";

       a[4] = "США";

       for (int i = 0; i < a.Length; i++)

           n[i] = i * 2 + 1;

       f.Zapis(a, n);

   }

}

}

Построение графиков и диаграмм

Вариант 7

 

 

 

 

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.Windows.Forms.DataVisualization.Charting;

 

namespace WindowsFormsApplication10

{

public partial class Form1: Form

{

   public Form1()

   {

       InitializeComponent();

       openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";

       dataGridView1.RowCount = 5;

       dataGridView1.ColumnCount = 3;

       dataGridView1.Columns[0].Name = "Страна";

       dataGridView1.Columns[1].Name = "Кол-во медалей";

       dataGridView1.Columns[2].Name = "% медалей";

   }

   int[] strana = new int[5];

   string[] Ns=new string[5];

 

   //Записывает данные

   public int Zapis(string[] a,int[] n)

   {

       int sum = 0;

       for (int i = 0; i < a.Length; i++)

       {            

           sum += n[i];

           dataGridView1.Rows[i].Cells[0].Value = a[i];

           dataGridView1.Rows[i].Cells[1].Value = n[i];

       }

       for (int i = 0; i < a.Length; i++)

       {

           if (n[i]!= 0)

               dataGridView1.Rows[i].Cells[2].Value = (Convert.ToInt32(Convert.ToDouble(n[i]) / sum * 100)).ToString() + "%";

           else

               dataGridView1.Rows[i].Cells[2].Value = "0%";

       }

       Diagram();

       return 0;

   }

 

   private void button1_Click(object sender, EventArgs e)

   {

       Ns[0] = "Россия";

       Ns[1] = "Великобритания";

       Ns[2] = "Украина";

       Ns[3] = "Польша";

       Ns[4] = "США";

       int sum = 0;

       for (int i = 0; i < Ns.Length; i++)

       {

           if (comboBox1.Text == Ns[i] && textBox1.Text!= "")

               strana[i] = Convert.ToInt32(textBox1.Text);

           sum += strana[i];

           dataGridView1.Rows[i].Cells[0].Value = Ns[i];

           dataGridView1.Rows[i].Cells[1].Value = strana[i];

       }

       for (int i = 0; i < Ns.Length; i++)

       {

           if (strana[i]!= 0)

               dataGridView1.Rows[i].Cells[2].Value = (Convert.ToInt32(Convert.ToDouble(strana[i]) / sum * 100)).ToString() + "%";

           else

               dataGridView1.Rows[i].Cells[2].Value = "0%";

       }

       Diagram();

   }

 

   private void Diagram()// метод рисует круговую диаграмму

   {

       chart1.Series.Clear();

       // Форматировать диаграмму

       chart1.BackColor = Color.Gray;

       chart1.BackSecondaryColor = Color.WhiteSmoke;

       chart1.BackGradientStyle = GradientStyle.DiagonalRight;

 

       chart1.BorderlineDashStyle = ChartDashStyle.Solid;

       chart1.BorderlineColor = Color.Gray;

       chart1.BorderSkin.SkinStyle = BorderSkinStyle.None;

 

       // Форматировать область диаграммы

       chart1.ChartAreas[0].BackColor = Color.Wheat;

 

       // Добавить и форматировать заголовок

       chart1.Titles.Clear();

       chart1.Titles.Add("Спорт");

       chart1.Titles[0].Font = new Font("Utopia", 16);

 

       chart1.Series.Add(new Series("ColumnSeries") { ChartType = SeriesChartType.Pie });

 

       string[] xValues = new string[Ns.Length];

       double[] yValues = new double[Ns.Length];

       for (int i = 0; i < Ns.Length; i++)

       {

           xValues[i] = dataGridView1.Rows[i].Cells[0].Value.ToString();

           yValues[i] = Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value);

       }

       chart1.Series["ColumnSeries"].Points.DataBindXY(xValues, yValues);

       chart1.ChartAreas[0].Area3DStyle.Enable3D = true;

   }

 

   private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

   {

       if (Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back))

           return;

       e.KeyChar = '\0';

   }

 

   private void button2_Click(object sender, EventArgs e)

   {

       if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)

           return;

       string filename = saveFileDialog1.FileName;

       string save = "Олимпийские игры" + Environment.NewLine;

       for (int i = 0; i < Ns.Length; i++)

           save += dataGridView1.Rows[i].Cells[0].Value.ToString() + Environment.NewLine + dataGridView1.Rows[i].Cells[1].Value.ToString() + Environment.NewLine;

       System.IO.File.WriteAllText(filename, save);

       MessageBox.Show("Файл сохранен");

   }

 

   private void button3_Click(object sender, EventArgs e)

   {

       if (openFileDialog1.ShowDialog() == DialogResult.Cancel)

           return;

       string[] txt = System.IO.File.ReadAllLines(openFileDialog1.FileName);

       for (int i = 0; i < Ns.Length; i++)

       {

           strana[i]= Convert.ToInt32(txt[2 + i * 2]);

           dataGridView1.Rows[i].Cells[0].Value = txt[1+i*2];

           dataGridView1.Rows[i].Cells[1].Value = strana[i];

       }

       int sum = 0;

       for (int i = 0; i < Ns.Length; i++)

           sum += strana[i];

       for (int i = 0; i < Ns.Length; i++)

       {

           if (strana[i]!= 0)

               dataGridView1.Rows[i].Cells[2].Value = (Convert.ToInt32(Convert.ToDouble(strana[i]) / sum * 100)).ToString() + "%";

           else

               dataGridView1.Rows[i].Cells[2].Value = "0%";

       }

       Diagram();

       button2.Enabled = true;

   }

}

}

 



Поделиться:


Последнее изменение этой страницы: 2021-05-26; просмотров: 160; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.137.218.230 (0.504 с.)