I'm new to C#, I need to overwrite label on windows form. I'm generating number of labels as per value of n using loop.
The issue: if I change the value of lines[i]
while running the program, the value does get changed but is not updated on windows form (previous value does not gets replaced by new one).
Can any one guide me how can I do that?
Also I'm refreshing the code every second using timer, which is also working fine
This is the part where I create the label and write the value in it, and it is in loop
Label label = new Label();
label.Text = String.Format("{0}", lines[i]);
label.Left = 10;
label.Top = (i + 1) * 25;
this.Controls.Add(label);
here is my complete code id anyone needs to check it:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Admin
{
public partial class Form1 : Form
{
string pathuser = @"//192.168.2.10/Shared-Public/Users.txt";
int check = 0;
public static string usernam;
string[] lines = new String[500];
string[] lines2 = new String[500];
public Form1()
{
InitializeComponent();
}
private void timer_Tick(object sender, EventArgs e)
{
tc = tc + 1;
Console.WriteLine(tc);
int c = 2;
int u = 0;
int us = 0; //for user pass
int z = 0; // for reading values from file
using (StreamReader sr2 = new StreamReader(pathuser))
{
string line;
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
us++;
}
}
for (int i = 0; i < us; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("{0}", lines[i]);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 25;
Label label2 = new Label();
label2.Left = 120;
label2.Top = (i + 1) * 25;
string line2;
string path = "//192.168.2.10/Shared-Public/" + lines[i] + DateTime.Now.ToString(" MM-dd-yyyy") + ".txt";
if (!File.Exists(path))
{
lines2[z] = null;
}
else
{
using (StreamReader sr3 = new StreamReader(path))
{
while ((line2 = sr3.ReadLine()) != null)
{
lines2[z] = line2;
z++;
}
}
label2.Text = String.Format("{0}", lines2[0]);
u = z;
z = 0;
}
PictureBox picbox = new PictureBox();
picbox.Location = new Point(240, 25 + (i*25));
picbox.Size = new Size(15, 15);
if (u%2==0)
picbox.BackColor = Color.Green;
else
picbox.BackColor = Color.Red;
u = 0;
this.Controls.Add(label);
this.Controls.Add(label2);
this.Controls.Add(picbox);
}
}
int tc = 0;
private void Form1_Load(object sender, EventArgs e)
{
Timer timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
}