Разработать визуальное приложение на языке с# в среде Visual Studio - C#
Формулировка задачи:
Разработать визуальное приложение на языке с# в среде Visual Studio. Для вывода массивов использовать dataGridView. Массивы заполняются случайным образом. Исходный и результирующий массивы выводятся в разные компоненты.
1) Дан массив, содержащий 15 элементов. Все положительные элементы возвести в квадрат, а отрицательные умножить на 2. Вывести исходный и полученный массив.
Вот мой код, но он считает суммы и выводит на компонент label, а мне нужно вывести весь 2 массив на компонент datagridview.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] mas = new int[5];
Random rand = new Random();
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.RowCount = 5;
for (int i = 0; i < 5; i++)
{
mas[i] = rand.Next(-5, 10);
dataGridView1.Rows[i].Cells[0].Value = mas[i];
dataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.AllCells);
}
}
private void button2_Click(object sender, EventArgs e)
{
int pol = 0;
int otr = 0;
for (int i = 0; i < 5; i++)
{
if (mas[i] > 0 ) pol += mas[i]* mas[i];
if (mas[i] < 0 ) otr += mas[i] * 2;
}
label3.Text = "Положительные элементы =" + pol;
label4.Text = "Отрицательные элементы =" + otr;
}
}Решение задачи: «Разработать визуальное приложение на языке с# в среде Visual Studio»
textual
Листинг программы
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int[] inputArray = getRandomArray(15);
showInGrid(inputArray, dataGridView1);
reworkArray(ref inputArray);
showInGrid(inputArray, dataGridView2);
}
private int[] getRandomArray(int nCount)
{
Random rnd = new Random();
int[] array = new int[nCount];
for (int i = 0; i < nCount; i++)
array[i] = rnd.Next(-100, 100);
return array;
}
private void reworkArray(ref int[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] > 0)
array[i] = array[i] * array[i];
else if (array[i] < 0)
array[i] = array[i] * 2;
}
}
private void showInGrid(int[] array, DataGridView dataGrid)
{
if (dataGrid.Columns.Count == 0)
dataGrid.Columns.Add("numColumn", "Number");
for (int i = 0; i < array.Length; i++)
{
int r = dataGrid.Rows.Add();
dataGrid.Rows[r].Cells[0].Value = array[i];
}
}
}