Is there anything in C# that is the opposite of IsNullOrEmpty - c#

I need to find something that is the opposite of IsNullOrEmpty?
Here's the text line.
{
while (string.IsNullOrEmpty(TextBox.Text))
}
What is the opposite of this?

{
while (!string.IsNullOrEmpty(TextBox.Text))
}

In the context of a Winforms TextBox control, you don't have to test the .Text property for null at all. Sadly, I can't find the documentation on this, and I fear it was a casualty of the mdsn => docs move, but I have verified it in Visual Studio.
You can verify it, too; try it. Make a simple project with a textbox, and set it's Text to null in code. Then check in the debugger, and you'll see it's actually set an empty string. The TextBox control is just nice that way, and so are most other stock Winforms controls.
With that in mind, the opposite of this code:
while (string.IsNullOrEmpty(TextBox.Text))
can reduce down to this:
while (TextBox.Text != "")
though you may want to also consider whitespace, which would be one of these two lines:
while (TextBox.Text.Trim() != "")
while (!string.IsNullOrWhitespace(TextBox.Text))
But now I need to bring up another point: none of these options does an Invoke on the control, meaning this must be running on the UI thread. It's very bad to run a while() loop like this on your UI thread. You're counting on the user to break the loop, but in the meantime you've blocked the entire user interface, where the program will have a hard time even processing the input that would eventually unblock it.
Instead, you need to handle a keypress event, or validate the textbox at the point where the user tries to initiate an action depending on the textbox value, or move this to another thread.

Related

How to clear the text inside a TextBox when it is being passed down in a function?

Here is what my code looks like:
private void exportToExcelButton_Click(object sender, EventArgs e)
{
txtBox.Clear();
txtBox.AppendText("Beginning Export...");
ExportExcel(txtBox);
txtBox.AppendText("Export complete...");
}
The problem I am having is that whenever the button is clicked (to execute the function above), only part of the current text in the TextBox (System.Windows.Forms.TextBox) is cleared, and replaced with the first line: "Beginning Export ...".
However once the function ExportExcel(txtBox) is done executing, then the entire text is replaced by the new one generated in ExportExcel(txtBox).
Inside ExportExcel(txtBox); I have several txtBox.AppendText() statements explaining to the user the actions being made.
I have tried clearing the text with txtBox.Text = String.Empty; and txtBox.Text = "";and neither have worked.
Let me know if anything needs to be clarified, thanks.
Looks like you're blocking the GUI thread, preventing the text box from redrawing itself. This is one reason why you shouldn't perform long-running tasks on the GUI thread. Use a background thread instead. That way you leave the GUI thread free to perform important operations like drawing, responding to mouse clicks, etc.
Have you tried the textBox.Refresh , before calling txtBox.AppendText("Beginning Export...").
The method invalidates the control.
On the other hand, if you use a background thread, then you should update the UI only by overriding the Progress Changed event. Background threads are not meant for updating user interfaces. Try searching for Worker threads and UI threads. They correlate to MFC, but the concept is the same.
Also keep in mind the cross thread calls.
I agree with dvnrrs. However if you are unable to do this, try calling txtBox.Refresh();after adding each line of text.
There is another method called Application.DoEvents(); that has a similar behavior, but its use is not recommended since it sort of short-circuits the normal application flow and can cause your application to fail unexpectedly or do strange things.

Find if TextBox.Text got changed by the user or by the code (Windows Phone 8)

I have a Windows Phone 8 project that converts values (i.e.: Celsius to Fahrenheit). There are two TextBox UI elements, one of which is read-only. The user can change the first TextBox to input the value to be converted. He can also press a button to "swap" the two TextBoxes so that he can do the reverse conversion. When the user presses the button, the value from the second TextBox goes into the first TextBox (and vice versa). But it's not the user who changed the value, it's the code who did.
I asked around (on IRC) and researched the subject, but I am a beginner and couldn't understand most of what I have found.
I heard that a simple solution would be to use Data Bindings. I researched the subject, and from what I read, Data Bindings can't solve my problem (correct me if I'm wrong).
I also tried to create a subclass of TextBox, hoping that I could hook in some custom event to it and go further in that direction. But I did not understand how to link the custom TextBox to the UI (in XAML). The way I created the subclass is to just create a new class and add TextBox as the parent. I know there is a template in VS to create a new User Control, and I tried it, but I couldn't understand what I was doing (or what I was supposed to do).
So I have two questions: Am I looking at the problem from the right angle? If yes, how do I create a custom TextBox and link it to the UI? If not, how could I solve my problem?
If your question is how to distinguish if the text got changed by the user or by the code then its simple.
Assuming that when the user types something you'd like to perform method A but when the code changes the text you'd like to perform method B:
In both cases you will need to override the TextBox.TextChanged() event handler.
You will also need a flag variable to tell you if the swap button was pressed or not.
The event handler should be something like this:
{
if (swap_pushed)
{
Method_B();
swap_pushed = false;
}
else
{
Method_A();
}
}
And finally your event handler for swap Button.Click() should be like this:
{
swap_pushed = true;
}

TextBox Scrollbar. Scrolling to end of TextBox within Thread

I've tried all the answers suggest in Stack Overflow to get my scrollbar to move to the bottom as text is being updated, but I have a feeling its not working because it's within a thread. My code is below ...
foreach(HtmlAgilityPack.HtmlNode paginationUser in paginationUsers) {
String userUrl = paginationUser.GetAttributeValue("id","");
this.Invoke((MethodInvoker)delegate {
txtLog.AppendText("...... Added " + userUrl + Environment.NewLine);
txtLog.Select(txtLog.Text.Length, 0);
txtLog.ScrollToCaret();
});
}
Is it the thread thats causing the code not to work? And what's a better solution?
Try to add this code :
TextBox.SelectionStart = txtLogEntries.Text.Length;
TextBox.ScrollToCaret();
at onTextChanged TextBox event .
I feel using this code is better:
TextBox.AppendText("your text")
it will automatically scroll to the end of the newly appended text & the auto scrolling animation seems more smoother compared to TextBox.ScrollToCaret() method
you can put this code at TextChanged TextBox event
I am having the same problem with WPF, using a thread to write to the textbox. It works fine until I add the ScrollToEnd.
I have no solution, just some remarks.
You are not locking the control. You should if you are filling it from a tread.
If I use Invoke it does work (but the UI becomes unresponsive). I use BeginInvoke, which is smoother but then it totally locks up if I use ScrollToEnd.
It seems to be some kind of triggering issue, one event causing the other.
Try feeding text slowly and see what happens, the worker thread may be flooding the textbox, giving it a really hard time, not allowing the main thread to do its thing.

C# WinForms: A function that executes more than expected

It sounds stupid, but this happens to me.
I activate a function, and it does its work, and after it finishes it enables itself again. With other words, the function activates twice, not once. I tried to find out why by debugging, but I didn't find the reason.
When I click on a panel this function activates:
private void Play(object sender, EventArgs e)
{
Play0(MousePositionX, MousePositionY);
if (swich_player == true && AI_enabled == true)
{
AI_playing();
swich_player = false;
}
}
The whole code is really long.
Is it me not searching correctly? Are there other reasons? In order for this function to start again, something has to activate it. I can't find what is activating the function again.
Any suggestions, where to search for the problem? Or what is the problem?
EDIT:
I finally found the problem. There is a button (button1) that changes the panel's properties, and a second button (button2) that makes the panel 0 pixels wide and 0 pixels high (in order to make it invisible). The first button also adds an EventHandler that activates the function. But button2 does not remove the EventHandler. This way the function gets called as much times as the times I have pressed button1.
Looks like what you're looking for (via your comments/edit) is the source of multiple calls to this function. With the current snippet of code, it's not possible for us to tell. But what you should do is put a breakpoint on the entry of the function and then when it is hit, look at the "Call Stack" window in visual studio.
This can be accessed via the Debug -> Windows -> Call Stack menu item (when running the program. It will not show up in Windows if you're not running)
You can then see what is calling your function through this window. It is an extremely useful tool.
Pre Edit:
Your question isn't very clear, but I think (from your variable names) that you're looking for a game loop that will continually run. If so, take a look at this blog post which has some very good information on different styles of game loops. It ranges from simple to more complex (and scalable) loops.
Your question states that you activate something once and it "enables again", and also that "In order this function to start again, something has to activate it. I can't find what". These seem to be contradictory statements. Can you edit your question to be a little clearer? If my answer is not what you were looking for after your edit, I will do my best to add whatever is needful.
check against which event you've registered this function. if you registered into to something no "OnClick" of that button, it might be the root cause

How do you manually refresh a window in WPF?

I'm using the ICommand interface to perform binding on a couple of buttons in my application, the Run and Close button. I'm using a helper method that was mentioned in this question to hook up the ICommand to a delegate as follows:
_someCommand = new DelegateCommand(this.DoSomething, this.CanDoSomething);
private ICommand _someCommand;
public ICommand SomeCommand
{
get { return _someCommand; }
}
private void DoSomething(object state)
{
// do something here
}
private bool CanDoSomething(object state)
{
// return true/false here is enabled/disable button
}
This appears to work just fine as, in my implementation, CanDoSomething returns the value of a property that I have in my application.
If I set the initial value of the property to true, then the button is enabled and false it is disabled.
I have a series of events that are raised from a BackgroundWorker in the application layer back to the ViewModel that change the value of the property to true or false based on the current state of the application.
The current problem I'm having is that the button is not "re-enabling" when I set the value to true after the work has completed. If I click somewhere within the window, it will update. So, therefore, I'm thinking than manually refreshing the window will solve my problem, at least for the interim. This feels a bit gross to do it this way, but I'm kind of at a loss for what else I could try.
If anyone has any suggestions, I'm all ears.
Thanks for the help!
Ian
Edit -
A little bit more information on the application itself. It uses a background worker in the application thread to handle the "work". The application is a simple utility to manage the creating of tables and loading of data into the tables. We use a lot of pre-defined SQL scripts to setup our test environment, so this is a simple utility that allows us to do that sort of thing based on parameters provided by the user in the UI.
Hopefully that helps, because when I re-read my question it read as if I were doing everything in the UI thread, which is not the case. Progress reports are raised back up to the UI thread and everything is updated as expected, except the button..
CommandManager.InvalidateRequerySuggested() may be the answer - it tells all the commands to check whether they are enabled or not.
You have to raise the CanExecuteChanged event:
http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.canexecutechanged.aspx
This may be more useful than the other answer in cases where you know you should re-evaluate a single control, and re-evaluating all the controls would be costly. The other answer is simpler if you don't have a case like that, though.

Categories