Programming for Everybody: CSharpTutorial| How to Calculate Sum, Max, Min, and Average from Dynamically Created TextBoxes 🔥

CSharpTutorial| How to Calculate Sum, Max, Min, and Average from Dynamically Created TextBoxes 🔥

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 WindowsFormsApp20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int newtextBox = 1;
private List<TextBox> txtbox = new List<TextBox>();
public TextBox AddNewTextBox()
{
TextBox ntextBox = new TextBox();
Controls.Add(ntextBox);
txtbox.Add(ntextBox);
ntextBox.Top = newtextBox * 27;
ntextBox.Left = 100;
ntextBox.ForeColor = Color.DarkBlue;
ntextBox.BackColor = Color.AliceBlue;
ntextBox.Font = new Font("Arial", 14, FontStyle.Bold);
ntextBox.TextAlign = HorizontalAlignment.Center;
newtextBox++;
return ntextBox;
}
private void button1_Click(object sender, EventArgs e)
{
AddNewTextBox();
}

private void button2_Click(object sender, EventArgs e)
{
label1.Text = txtbox
.Select(t => decimal.TryParse(t.Text, out decimal value) ? value : 0)
.Sum()
.ToString("0.00");
}

private void button3_Click(object sender, EventArgs e)
{
if (txtbox.Count == 0) return;
label1.Text = txtbox
.Select(t => decimal.TryParse(t.Text, out decimal value) ? value : 0)
.Max()
.ToString("0.00");
}

private void button4_Click(object sender, EventArgs e)
{
if (txtbox.Count == 0) return;
label1.Text = txtbox
.Select(t => decimal.TryParse(t.Text, out decimal value) ? value : 0)
.Min()
.ToString("0.00");
}

private void button5_Click(object sender, EventArgs e)
{
if (txtbox.Count == 0) return;
label1.Text = txtbox
.Select(t => decimal.TryParse(t.Text, out decimal value) ? value : 0)
.Average()
.ToString("0.00");
}

private void button6_Click(object sender, EventArgs e)
{
foreach(TextBox tb in txtbox)
{
tb.Text = String.Empty;
}
label1.Text = "";
}

private void button7_Click(object sender, EventArgs e)
{
foreach (TextBox tb in txtbox)
{
Controls.Remove(tb);
tb.Dispose();
}
txtbox.Clear();
newtextBox = 1;
label1.Text = "";
}
} 

} 

No comments:

Post a Comment