Being a beginner in C# I am having problem in a specific implementation. I need to compute two data in real time by which I mean ki the output shows as soon as the inputs are provided with no click of button necessary.
- For example I have a Text Box where if a type a number 5 gets added to it and the output shows in a Label. The label automatically updates when more numbers are typed in real time.
How do I achieve this?
Thanks !
Before explaining the specifics, it's important to point out that from the code's perspective there isn't much difference between clicking a button or responding to the TextBox's event. Here's what I mean.
In addition to calling code procedurally from within your own methods like this:
void MyMethod(argument)
{
...Other Code...
DoSomething(argument);
...Other Code...
}
.Net also allows you to attach method calls to Events. Events are just references to delegates(I'll leave it up to you to research delegates), but they allow you to asynchronously execute your code based on external interaction.
In your question you say that you want to perform a calculation without making the user click a button. Before going into how you'll accomplish that, lets think about what you'd do if there were a button. Chances are you'll drag & drop a button onto the designer surface, then double click it. Behind the scenes you'll suddenly have a method that looks something like this:
void button_ButonClick(object sender, ClickEventArgs args)
{
DoSomething();
}
So you'll go and populate the new method's body with your calculation logic. Under the hood you've actually just had the designer hook that new method up to the Button's click event. So in your case, whether you're adding the calculation logic to a button click or the TextBox's TextChanged event, you're actually doing almost the same thing.
Just for reference, here's the MSDN documentation for TextBox's TextChanged event .
OK I will give it a shot :)
Assume two textboxes and a label on a form.
Each textbox has a text_changed event handler, i.e. if you type something in either text box, the event handler code is called and there you can access the text of each textbox and transform the text into two numbers.
Then you compute the 2 numbers as per your rules and the result is displayed in the label.
This is a very simplified explanation! There must be validation of the inputs in the textboxes to ensure the data format is correct.
Ask more questions if this is not clear enough.
Related
I am creating buttons dynamically for a user-based app. Now I have to tell the new form what text to apply to the buttons via parameters to the form, the form then creates the buttons. Now I have an issue - the events for these buttons: What is the best mechanism to get the button click events through. I cannot access the form from the originating form, and I can only pass simple data types (and arrays).
My first thought is to use a code to reffer to the appropriate method in a static class - basically, pass an array of ints through with the names of the buttons and their onclick handler calls one method - handle(int code) -> where code is used in a giant switch statement to call the appropriate method.
But I doubt this is the best mechanism. I would prefer to create a listener of some sort that simply listens for button clicks, and should the click be unhandled, determine which button was clicked and manage it from there.
I have looked at the observer pattern and I am not entirely convinced this is the best one to follow. The problem is not that there is no solution, the problem is that I want the BEST solution.
This is in C# for monodroid - but the impact of this information should be minimal.
Thanks
Not sure to fully understand what's actually your problem, but here's how you should deal with dynamic controls and event handlers:
Button myNewButton = new Button { Text = "MyCaption" };
myNewButton.Click += (sender, e) =>
{
((Button)sender).Text = "New text here!";
// Another logic could be put here
};
If it was WPF i'd use Commanding but i don't know if it's available for monofroid.
You may look at http://www.codeproject.com/KB/dotnet/EventBroker.aspx
Currently I have two options:
Use reflection - pass a method name to the button and that button can then invoke a method based on the string value passed. Then simply create a static class where all button methods are kept.
Use a switch statement - since I can have delegates that take parameters (one of them being a SENDER object) I can easily send the sender object to a method containing a switch statement which performs an action based on that object.
In my research I have determined that the former (reflection) is preferred, espcially since the number of buttons is rather large.
REFS:
http://embeddedgurus.com/stack-overflow/2010/04/efficient-c-tip-12-be-wary-of-switch-statements/
Large Switch statements: Bad OOP?
Method Factory - case vs. reflection
Please guide me as how to save/discard values of controls of a form, upon pressing Ok/Cancel button accordingly in Visual Studio C#?
Controls in a form include TablelayoutPanel(TextBoxes), NumericUpDown.
Need your expert guidance
Regards
Asad
With both of your buttons, inside the "onclick" event, call a function that will save the content of the form. You also need this call in the "onclose" event of the form, in case the user presses the top-right X button (or not, if you dont want data to be saved at that moment)
Inside that function, you will need some code that will save data to the registry.
Writing in the registry is easy. This webpage also explain how to get the data back. The values you will write will be the textbox.Value and such
The question isn't clear, but in a WinForm you can call
this.Close()
on the Click event of your Close button.
Every object or variable used by the form will be destroyed. Be careful! running background threads will still be alive until they terminate.
About saving the status of your variables it completely depends on what you need to with them after; you can either keep them in memory and pass them around like parameters or write on a disk (maybe with serialization?).
We need to know more.
edit
You may want to take a look at Application Configuration ( http://msdn.microsoft.com/en-us/library/ms184658(VS.80).aspx ).
I'm making simple C# Winform application. There is a Form having a textbox. I want to change the location of textbox by arrow key but textbox has the input focus so form's KeyDown event is not called. How can I remove that input focus?
Typing on the textbox should still be possible. I try to make a dummy label and give the focus, but It doesn't work. If I press any key, the cursor go back to the textbox. please help me. How can I solve this problem?
Handle the TextBox.KeyDown event. And set e.Handled = true; in your handler after you move the TextBox, but before you return. And, yeah, only handle the arrow keys.
Hmm, not sure if I understand. If the user can type into the edit box, then it can have focus. If he clicks outside of it, on a blank are of the form, then it loses focus.
If you want to be able to 1) type into the edit box and 2) move the edit box, then you need a separate mechanism to enter "move mode".
I would suggest either a "click here to move selected control" button, or a right-click context menu on the control with a "move control option".
You would also have to conisder how the user indicates that moving has ended.
Hope this helps.
NOTE: I just realized this is not even an in-browser C# app. I guess disregard all of this. Serves me right for not reading carefully enough.
Use Javascript, in particular, I'd personally recommend jQuery.
They have pretty nicely documented their library: http://docs.jquery.com/Main_Page
For this particular task, you are going to want to bind some sort of key event (ie. keypress) and make sure to stop event propagation (so that you prevent the default response which is to be sent to be simply handled by the textbox element's default listener).
So, to give you an idea, if you want to change the location of the textbox using keypresses (maybe arrow keys), do something like this:
/* link the jQuery source to the HTML page with script tag */
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
/* short hand for $(document).ready(function() { ... */
$(function() {
$("#textbox_id").keypress(function(e) {
var $this = $(this); // store the #textbox_id element in $this
e.preventDefault();
switch (e.keyCode) {
// find the actual integer code for the up arrow
case UP_ARROW:
$this.animate({
top : '-=10px'
}, 100); // time in milliseconds to complete the animation
/* fill in the cases */
}
}
});
Okay, I hope you get the picture. Find out more about animate() and other jQuery functions at in the documentation at the link I provided above. Hope that helps!
NOTE: Obviously, preventing the default handling of events is a terrible idea in this case for accessibility reasons. Use your best judgement when selecting keypresses to trigger these moving events -- whatever you do, don't disallow users from moving around within the text they have in input fields.
Did some searches here & on the 'net and haven't found a good answer yet. What I'm trying to do is call a button twice within the same class in C#.
Here's my scenario -
I have a form with a button that says "Go". When I click it the 1st time, it runs through some 'for' loops (non-stop) to display a color range. At the same time I set the button1.Text properties to "Stop". I would like to be able to click the button a 2nd time and when that happens I would like the program to stop. Basically a stop-and-go button. I know how to do it with 2 button events, but would like to utilize 1 button.
Right now the only way to end the program is the X button on the form.
I've tried different things and haven't had much luck so far so wanted to ask the gurus here how to do it.
BTW, this is a modification of a Head First Labs C# book exercise.
Thanks!
~Allen
You would need to use Multithreading (launch the process intensive code asynchronously in a separate thread), for instance, using the BackgroundWorker object in .NET 2+. This would be necessary because your UI will not respond to the user's click until the loop running in the Start method is completed. It is quite irrelevant if you use the same button or another one to toggle the process, because the processor is busy processing the loop.
The BackgroundWorker has a property called WorkerSupportsCancellation which needs to be true in this scenario. When the user clicks Stop you would invoke the CancelAsync method of the BackgroundWorker.
See MSDN for a good example. Also DreamInCode has a good tutorial which seems quite similar to your requirement.
Why not create two buttons, hide one when the other is visible? That should be a lot of easier to handle.
Or you can add a bool field to indicate which operation branch to execute.
One simple solution would be to add a boolean member to your form that is, e.g., true when the button says "Go" and false when the button says "Stop".
Then, in your button's event handler, check that boolean value. If the value is true, then start your operation and set the value to false when you change the button's text to say "stop". Vice-versa for the other case. :)
There are other techniques that I might prefer if this were production code, perhaps including considering the design of the form more carefully, but as this is clearly a learning exercise I believe that a simple boolean flag indicating the current state of the form is just what you're looking for.
Note that I would strongly discourage you from checking the value of the button text to determine what state the object is in. Whenever possible, as a general rule of good design, you want your visual state to be "decoupled" from your underlying object's state. That is to say, your visual widgets can depend on your underlying objects, but your underlying objects should not depend on your visual widgets. If you tested the text of the button, your underlying logic would depend on your visual state and that would violate this general rule.
If your problem is related to the fact that you can't cancel the operation while it's being performed, you'll want to look into using a BackgroundWorker to perform your long-running activity.
Another option would be to check the current text on your button to determine what to do:
void btnStartStop_Click(Object sender, EventArgs e)
{
if (btnStartStop.Text == "Go")
{
btnStartStop.Text = "Stop";
// Go code here
}
else
{
btnStartStop.Text = "Go";
// Stop code here
}
}
Are you getting your second button click event? Put a breakpoint in your click handler and run your code. When you click the second time, do you ever hit your breakpoint?
If your loop is running continuously, and it is in your button click handler, then your loop is running in the UI thread. You probably don't get to "see" the second button click until after the loop is completed. In addition to the branch code that you see above, try either inserting a DoEvents in your loop processing (this is a place where your loop will temporarly give up control so that messages can be processed). Or, (better) have a look at the backgroundworker class -- do most of your processing in a different thread, so that you UI can remain responsive to button clicks.
Cerebrus is right about using the Background Worker thread. However if you are doing a WPF app then it won't be able to update the UI directly. To get around this you can call Dispatcher.BeginInvoke on the main control/window.
Given code like:
Private Delegate Sub UpdateUIDelegate(<arguments>)
Private Sub CallUpdateUI(<arguments>)
control.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Background, New UpdateUIDelegate(AddressOf UpdateUI), <arguments>)
End Sub
Private Sub UpdateUI(<arguments>)
'update the UI
End Sub
You can call CallUpdateUI from the Background Worker thread and it will get the main thread to perform UpdateUI.
You could set the Tag property on the button to a boolean indicating whether the next action should be "Stop" or "Go", and reset it each time you click the button. It's an Object property, though, so you'll have to cast it to bool when you read it.
Simplifying
I have a text box and a button
The button just create an messagebox with the text from the textbox.
But i change the value of the textbox, the new value apears (Ex: Type 123) but the message box does not show the value.
If i try to use the value in the programming (get the value by textbox1.text) the variable has nothing ( textbox1.text = "") but i can still see what i typed in the form.
Anyone has any clue?
Your button's click event handler should look something like this
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox.Text);
}
I suspect you already have code similar to this and that at some point the textbox is cleared or otherwise set to String.Emppty but without seeing actual code it is difficult to help you
When/where did you check the value of textBox1.Text? If you're checking it in the constructor, Form1_Load, or anything else that occurs before you'll have typed text, you will get an empty value.
To properly check the value of textBox1.Text, you should set what's called a breakpoint on the line that calls MessageBox.Show(textBox1.Text). To do this, click in the grey area of the source editor (it's on the far left) on the line containing MessageBox.Show(..). A red circle will appear and your code should be highlighted. When you run your application and click on your button, your application should pause and Visual Studio will highlight that line and from here you can hover over "textBox1.Text" in the MessageBox.Show() line and it should show you the current value.
If your application is as simple as a form, a textbox, and your button1_Clicked event handling code, this should work no problem. If it is not this simple, then you need to look for anything that sets the value of the textBox in your code and make sure it isn't passing any blank values by using breakpoints.
To solve this properly, though, we really need more information.
Thanks Eric and Crippledsmurf. As both of you said, its hard to help without the code.
The problem I found is that when calling the form, I send some objects by reference, so I can track them down and I found that when (don't ask me why it happens that way, I'm still working on it) the construtor is called he make an new component, so the component in the interface no longer represents the one pointed by the variable "textbox1" (Yes Crash893, I haven't mispelled the name).
I found that I was making some mess with the references, and probably that was causing the problem. I fixed the problem by changing the actions performed by references for delegates and events, but I couldn't track down the exactly source of the problem.
Thanks, again, everyone for the insights.