c# form application label does not update - c#

Hi everyone this is my first question to stackoverflow and sorry for my English. I searched for a week and couldn't find the solution. I am working on a project which uses RFID antenna and tags . A machine reads the tags and produces tag id like bcbc 0000 or abab 1111 ... Every id points a unique product like shirt , panth etc.This program is a product counter. My form application uses this id's matches with the products and counts them. When program gets a shirt id I want to increase "shirt count label" on the form at the reading time. I wrote 2 different programs and both didn't update the label.
my codes :
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Interval = 2000;
aTimer.Start();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
reading part is below;
reader.Connect(SolutionConstants.ReaderHostname);
Settings settings = reader.QueryDefaultSettings();
settings.Report.IncludeFastId = true;
settings.Report.IncludeAntennaPortNumber = true; // WS
settings.Antennas.GetAntenna(1).MaxTransmitPower = true;
settings.Antennas.GetAntenna(1).MaxRxSensitivity = true;
settings.Antennas.GetAntenna(2).MaxTransmitPower = true;
settings.Antennas.GetAntenna(2).MaxRxSensitivity = true;
...... and other settings here....
// Apply the newly modified settings.
reader.ApplySettings(settings);
// Assign the TagsReported event handler.
// This specifies which method to call
// when tags reports are available.
reader.TagsReported += OnTagsReported;
// Start reading.
reader.Start();
in OntagsReported() function i do some controls and the important part is
tagList.Add(tag.Epc.ToString()); // adds tags to tagList.
timer function ;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
for (int i = 0; i < tagList.Count; i++)
{
if (!usedTags.Contains(tagList[i]))
{
//MessageBox.Show("");
label1.Text = "Text Updated.";
//productCounter(tagList);
usedTags.Add(tagList[i]);
}
}
}
Everything is working . Program goes last if control. If I write there a messageBox it shows that but on the next line label does not change. Thanks for help :)

System.Windows.Forms.Timer instead of System.Timers.Timer could help you.
System.Timers.Timer fires event in the non-UI thread,
so you should not access UI controls directly in the event handlers.

Seems like you need to marshal the call to the UI thread.
label1.BeginInvoke(new Action(() => label1.Text = "Text Updated"));

Related

Label text value does not change after executing an elapsed event callback

Hi all I'm still new to the c# events and timers but it seems I have a bug that baffles me despite following seemingly working code online. I have a simple search function that is triggered after a timer elapses. Before that function triggers I set the result title to "Search in progress..." and at the end of the process i expect it to change to "1152 results found". But the label doesn't change eventhough in debug i hit the code sets it and i even see that the searchresultTitle.Text value is changed and the "list" actually contains 1152 items. The website just doesnt reflect it, is there something wrong with the way I setup the timers or am I missing something?
protected void StartSearchClick(object sender, EventArgs ev)
{
String textVal = Request["SearchBox"];
textVal = textVal.Replace('*', '_');//to support * as wildcard
String publicChoice = PublicChoice.SelectedValue;
int iChoiceVal = 1;
Int32.TryParse(publicChoice, out iChoiceVal);
SearchResultTitle.Text = "Search in progress...";
System.Timers.Timer aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += (s, e) => ReadPublishedLessons(textVal, iChoiceVal);
aTimer.AutoReset = false;
aTimer.Start();
}
private void ReadPublishedLessons(string namePart, int iPublic)
{
//null check
if (namePart == null)
return;
eon.LessonInfo[] list = WsAdmin.GetLessonList(namePart, iPublic);
SearchResultTitle.Text = list.Length + " results found";
}
Answered by Bharadwaj in the comments...
In case of asp.net, the html is sent back to the client side only after a post back or a partial post back. At the end of your event trigger call, the html which is ready is already reached to the client with Search in progress... message. But when you try to change the value of label, it is changing and it is still at server only. – Bharadwaj Jul 15 '16 at 4:45

pause rich text box and then resume again

What I am doing:
I am receiving a string of data every second constantly from a serial port. I am processing it and also displaying this string on the rich text box.
Problem:
I want the user to go through the old strings and copy any, but user can't do it because data is coming every second and auto-scrolling occurs.
My desired solution:
I am thinking to have a check-box 'pause'. when user checks it updating of rich text box stops. and user can go in history and copy a string. but in the mean while I don't want to stop the incoming strings from the serial port as I am doing other things as well with the incoming strings.
So when user uncheck 'pause' checkbox, all the strings which had arrived earlier while user had checked' pause' checkbox also appear on rich text box along with new ones.
is there a way to do it ?
Suppose that when you check the Pause button then every incoming text is appended to a StringBuilder instead of the RichTextBox. When the user uncheck the Pause button you copy everything from the StringBuilder to the RichTextBox
// Assume that these are somewhere globals of your forms
RichTextBox rtb = new RichTextBox();
CheckBox chkPause = new CheckBox();
StringBuilder sb = new StringBuilder();
protected void chkPause_CheckedChanged(object sender, EventArgs e)
{
if(!chkPause.Checked)
{
rtb.AppendText = sb.ToString();
// Do not forget to clear the buffer to avoid errors
// if the user repeats the stop/go cycle.
sb.Clear();
}
else
{
// Start a timer to resume normal flow after a timer elapses.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = GetSuspensionMilliseconds();
t.Tick += onTick;
t.Start();
}
}
protected void onTick(object sender, EventArgs e)
{
if (chkPause.Checked)
{
// Set to false when the timing elapses thus triggering the CheckedChanged event
chkPause.Checked = false;
System.Windows.Forms.Timer t = sender as System.Windows.Forms.Timer;
t.Stop();
}
}
now in the point where the incoming data is passed to the RichTextBox you could add
....
string incomingData = ReceiveDataFromSerialPort();
if(chkPause.Checked)
sb.AppendLine(incomingData);
else
rtb.AppendText = incomingData;

How to define a timers interval from a textbox in C#

I am learning C# and I am coding a simple auto typer, and I am trying to make it so users' can set their own interval. I tried using:
timer1.Interval = textbox1.Text;
but that doesn't seem to be working. I put that code in a button.. How do I get this to work? And why isn't it working?
You could use something like this:
int value;
// if it is really a value
if (int.TryParse(textbox1.Text, out value))
{
// if the value is not negativ (or you can enter the lower boundary here)
if (value > 0)
{
timer1.Interval = value;
}
}
As Steve mentioned in his comment, you need to connect a callback function to the timer1.Elapsed event (Attention: The name of the event differs depending on the timer you are using. It could also be timer1.Tick). You would do this by using the following code:
timer1.Elapsed += TimerElapsedCB;
and you need to define the callback function itself:
private void TimerElapsedCB(object sender, ElapsedEventArgs e)
{
// Do something here ;-)
// (e.g. access the signal time by using e.SignalTime)
}
try this :
Timer timer1 = new Timer();
timer1.Interval = int.Parse(textbox1.Text);
but keep in mind that user must enter a number , so you might need to handle the case when the user enter wrong data .
Edit :
You might use TryParse to make sure it's a number :
int myInt = 0;
Timer timer1 = new Timer();
bool parsed = int.TryParse(textbox1.Text,out myInt);
if (parsed)
{
timer1.Interval = myInt;
}

How to continuosly update the textbox in C#

I have the following piece of code:
class NotepadCloneNoMenu : Form
{
protected TextBox txtbox;
public NotepadCloneNoMenu(string a)
{
Text = "Notepad Clone No Menu";
txtbox = new TextBox();
txtbox.Parent = this;
txtbox.Dock = DockStyle.Fill;
txtbox.BorderStyle = BorderStyle.None;
txtbox.Multiline = true;
txtbox.ScrollBars = ScrollBars.Both;
txtbox.AcceptsTab = true;
txtbox.AppendText(a);
txtbox.AppendText("\n");
}
}
class program1
{
public static void Main()
{
string result = "abc";
while(true)
{
Application.Run(new NotepadCloneNoMenu(result));
}
}
}
I want to continuously appending the string result to the textbox so it looks like this:
abc
abc
abc
so on and so forth. However, every time I called this:
Application.Run(new NotepadCloneNoMenu(result));
It will reset the textbox. Is there anyway I can update the textbox continuously? I am fairly new to C# so this is quite confusing to me.
thanks,
Phuc Pham
First of all, you're continuously closing and opening an application. That's why it resets. If you want to run an infinite loop, you probably want to run it inside your application proper.
In your application code, use some event (maybe a timer would suit you) to append text to the textBox. Like this:
public someEventOnTheForm (object sender, EventArgs e)
{
txtBox.Text += "Notepad Clone to Menu";
}
There's two more things to take into account: first, if you don't have a stoping condition, this will just keep filling memory until you run out of it.
Second, windows forms run on only one thread by default. You'll be using that thread to update the textbox, so while it's appending text, the form itself will be unusable. It'll probably blank out during the event if it starts taking long. You'll need a second thread to handle the event if you want your form to be usable.

Looping Text label in C#?

i have a timer that changes a label's text each tick. For some reson, it stop and does not continue looping. Why?
private int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] arr4 = new string[3]; // 4
arr4[0] = "one";
arr4[1] = "two";
arr4[2] = "three";
if (count == 4)
{
count = 0;
}
toolStripStatusLabel1.Text = arr4[count];
count++;
}
Also, when my form loads, the label's text is blank. Then it goes to arr4[0]. When it loops again, the text starts at arr[0]. Why is the text blank first, and how do i fix it?
Looks like your original question was answered in the comments. I'll answer your second question from the comments.
Your timer1_Tick event doesn't execute immediately when your program starts. The first time it executes is after 5000ms, in your case. So the label will show blank at first, then change to the value of arr4[0]. If you don't want that, you could:
set the value of the label in the designer at design time
set the value of the label in the constructor at run time
pull the creation of the array out of the timer tick event so you're not recreating it every 5 seconds, make it a class variable, and create it in the constructor and then set the label to arr4[0] immediately after creating it

Categories

Resources