Making a text box become visible hides all formatting - c#

I am currently making a windows form application on Visual studio in C#. I have a couple of text boxes where I want the user to input some stuff and then this information is checked whether it exists, if not, an error is thrown and a text box saying "Invalid File" is meant to appear, in red.
However, currently, when I enable it's visibility, it simply shows up as a blank box, with no colour and no formatting.
Here is the code I was using:
catch
{
textBox9.Visible = true;
System.Threading.Thread.Sleep(3000);
textBox9.Visible = false;
}

The only thing it happens is the txtbox be visible, so the only code executed is the code inside catch...
Try to set all the properties in the catch, something like that:
For sure all gonna be executed now.
catch
{
textBox9.Text = "Invalid File";
textBox9.BackColor = Color.Red;
textBox9.Visible = true;
Thread.Sleep(3000);
textBox9.Visible = false;
}
Edit:
I saw the comment, and that's right Thread will block all the code for 3 seconds.
So I've other option, something like that:
catch
{
textBox9.Text = "Invalid File";
textBox9.BackColor = Color.Red;
textBox9.Visible = true;
int seconds = 3;
if (seconds < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(seconds);
while (DateTime.Now < _desired)
{
System.Windows.Forms.Application.DoEvents();
}
textBox9.Visible = false;
}

If i understand correctly you are trying to make the textbox work over 3 seconds and then go away, if that is so the code you need would look like this
Task.Run(async () =>
this.Invoke(new Action(delegate (){
textBox9.Visible = true;
await Task.Delay(3000)
textBox9.Visible = false;
}));
EDIT: This code is needed because you dont wanna hang the whole thread just wait 3 seconds and then make it go away, the way you are doing it, you are freezing the whole application if you are not using threads
EDIT2: It isnt showing anything because you are freezing the thread before it draws on your screen and then you are setting the textbox hidden. So nothing will show

private void DisplayError()
{
Task.Run(async () => (
this.Invoke(new Action(async delegate () {
textBox9.Visible = true;
await Task.Delay(3000);
textBox9.Visible = false;
}))));
}
Thanks to nalnpir for the basis of this. This works for me.

Related

Xamarin Forms Switch with Task

So I'm new in programming with Xamarin (actually even with C# tbh)
What I'm trying to acheave is a Task which should only work when a Switch (called S1) is Toggled.
My idea:
public async Task GetCon(){
for (; ; )
{
if (S1.IsToggled == true)
{
AI1.IsRunning = true;
bool CStat = await CrossConnectivity.Current.IsRemoteReachable("https://www.google.ch");
if (CStat == true)
{
StatLbl.Text = "Online";
}
else if (CStat == false)
{
StatLbl.Text = "Offline";
break;
}
off:;
await Task.Delay(3000);
}
All works fine but if I turn the Switch back off and make google unreachable, the StatLbl text doesn't change to offline.
Any idea?
As you're new to C#, I'm surprised no-one else has picked up on this, but here goes.
Instead of infinitely running a Task and waiting for the switch to be toggled, use the Toggled event to trigger when the toggle status changes. How does it work? When you toggle the switch, your program will automatically call that method. For example:
public MyConstructor()
{
S1.Toggled += S1_Toggled;
}
void S1_Toggled(object sender, ToggledEventArgs e)
{
System.Diagnostics.Debug.WriteLine(String.Format("Switch is now {0}", e.Value));
}
You can find more information (and some example) for the Switch at the Xamarin Forms Docs.
As Jason pointed out, you should be modifying UI properties from the UI thread. Properties like colour, visibility, text etc (anything that changes on the display) should be done in Device.BeginInvokeOnMainThread like so:
Device.BeginInvokeOnMainThread(() =>
{
StatLbl.Text = "Offline";
});
you need to execute UI changes on the UI thread
Device.BeginInvokeOnMainThread(() => {
StatLbl.Text = "Offline";
});
Most of the code executes only when the switch is on, you have this line that prevents from changing the label name when the switch is on:
if (S1.IsToggled == true)

Cancel Video Conversion

I have developed a PowerPoint addin that converts the currently open presentation to a .wmv file.
It all works nicely. When the presentation is converting I can see a progress bar at the bottom of PowerPoint along with a red X which can be pressed to cancel the conversion process.
Is there a way of programmatically calling this cancel button some how?
This is the code I use to call it and wait for it to finish but I would also like to be able to cancel it while it's in progress.
private void frmUpload_Load(object sender, EventArgs e)
{
try
{
progressBarUpload.Value = 0;
string exportName = "video_of_presentation";
string exportPath = #"C:\Windows\Temp\{0}.wmv";
// Export the currently open presentation
Microsoft.Office.Interop.PowerPoint.Application ppApplication = null;
ppApplication = new Microsoft.Office.Interop.PowerPoint.Application();
ppApplication.Activate();
ppApplication.ActivePresentation.SaveAs(String.Format(exportPath, exportName), Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsWMV);
lblUploadStatus.Text = "Status: Converting …";
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
/* run your code here */
do
{
System.Threading.Thread.Sleep(500);
}
while (ppApplication.ActivePresentation.CreateVideoStatus != Microsoft.Office.Interop.PowerPoint.PpMediaTaskStatus.ppMediaTaskStatusDone);
backgroundWorker.RunWorkerAsync();
SetControlPropertyValue(lblUploadStatus, "text", "Status: Uploading …");
}).Start();
}
catch
{
lblUploadStatus.Text = "Status: Error Converting File.";
}
}
Any help would be much appreciated.
Trev
According to MSFT this is not possible :(
Thread is here:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/9308ca45-ec8e-42df-8a5f-a150468a6213/cancel-microsoftofficeinteroppowerpointppsaveasfiletype
Trev

Calling method from within Form1 OR Calling buttons and text fields from another class?

Alright so:
I have in Form1 a restart() method that restarts my game, it also changes the labels, textfields, groupboxes etc to visible again.
I need this method to be in Game.cs, problem is, C# gives me loads of errors when I put this method in Game.cs
So I was wondering how I can either
- Call a Form1 method from within Game.cs
- Make the txts, lbls, and etc change work withing Game.cs
Thank you so much.
EDIT : Here's the restart method
public void restart() {
lblBeschrijving.Visible = true;
gbNaam.Visible = true;
lblNaam.Visible = true;
txtNaam.Visible = true;
gbMuren.Visible = true;
cmbMuren.Visible = true;
lvlMuren.Visible = true;
gbMoeilijkheid.Visible = true;
cmbMoeilijkheid.Visible = true;
lblMoeilijkheid.Visible = true;
picBeginscherm.Visible = true;
btnSpelen.Visible = true;
tmrSnake_Tick.Enabled = false;
nFoodTeller = 0;
foodExtra.nEnabled = true;
nScore = System.Convert.ToInt32(snakeScoreLabel.Text);
snake = new Snake();
DialogResult error;
error = MessageBox.Show("Oh no! You killed the snake!\nDo you wish to play Again?\n\nYou scored " + nScore, "Snake Game Error", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
// ..and the snake's dead!
if (error == DialogResult.No) {
Close();
}
}
I'm assuming I'm on the same level as you on programming games on c#. So here's my experience:
Game logic and UI are 2 separate entities, and UI controls the game not the other way around. This making sure that if the UI changes the game works anyway. Way to achieve this is to declare events and delegates that your main UI can hook into. So when you fire an event the UI receives the info. For example I used events to update the Score of Tetris:
https://subversion.assembla.com/svn/xand-tetris/trunk/
good luck exploring

changing visibility not working

I have a Label and PictureBox element that in designer i set visibility as false.
now i try this :
private void openExcelButton_Click(object sender, EventArgs e)
{
openExcelDialog.Filter = "Excel files|*.xls;*.xlsx;*.csv";
DialogResult result = openExcelDialog.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
LoadingGIF.Visible = true;
LoadingLabel.Text = "Loading...";
LoadingLabel.Visible = true;
string file = openExcelDialog.FileName;
//more code
LoadingGIF.Visible = false;
LoadingLabel.Text = "Uploading Finished!";
}
}
Now when pressing the button and choosing a file nothing happens untill i finish the code in the //more code section and then the label changes.
Why does this happen?
The reason this happens is because your main thread is becoming non-responsive and not allowing the changes to happen in a sequential order. I had a very similar issue on a project a year ago. The suggested solution by MS is to use a background worker to open the file and manipulate it so the primary thread does not become non-responsive. Microsoft has a fairly decent example of how to use a background worker here: http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

How to update text in a label

I have here a long method that takes a little while to execute. I would like to keep the user entertained so I created a progress bar and a label. What I would like is for that label to change while the system executes the progress. Ive been looking at Application.DoEvents(), but it seems like thats the wrong way to go. This application is pretty simple and its just a project and nothing professional. All this app does is send a file to a client and insert the data into a database.
I have one label (besides a success and error label), that I would like to constantly update along side the progress bar. Any ideas or tips on how to do this? Would Application.DoEvents() be acceptable in this situation? Or is there a simple way to update the text. I am using C#, asp.net, and a System.Web.UI.Page. Any help or pointing me to the right direction would be greatly appreciated.
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
//label text change here
if (btn.ID == PutFTPButton.ID)
{
//bf.ReadyFilesForTransmission();
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
//label text change here
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
//label text change here
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
//lblWait.Visible = false;
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = true;
SuccessLabel.Visible = false;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
I think you can use an Ajax UpdateProgress control, check Progress Bar on File Upload ASP.NET.
EDIT: Another one Displaying Progress Bar For Long Running Processes using ASP.NET AJAX.
Application.DoEvents() is not available in an ASP.NET application, nor is it's use acceptable in a standard WinForms application with the advent of multicore processors and the .NET threading library.
A web application requires communication to/from a server. Therefore simply updating the text of a label does nothing unless you are sending that back to the client. In your case you would need an event which was signaled by this line (because it is a batch upload):
transmit.UploadBatchFilesToFTP(BatchFiles);
The event would update the value you want to display. You would then need some AJAX code (or an ASP.NET update panel around a ASP.NET label) on the web page in question to get and display the new value.
HTH
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.label1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else this.label1.Text = text;
}
void SomeMethod()
{
SetText(yourVariable.ToString());
}
if i understand you correctly this should work.

Categories