How to prevent an event from being executed on form load - c#

I have the following code when loading the form
private void LlenarCampos()
{
NombreProducto.Text = productos.Nombre;
ID.Text = productos.Producto_ID.ToString();
Codigobarrafrm.Text = productos.CodigoBarra;
Existenciafrm.Text = productos.Existencia.ToString();
precio1frm.Value = (decimal)productos.Precio1;
beneficio1frm.Value = (decimal)productos.Beneficio;
Costo.Value = (decimal)productos.Costo;
Existenciafrm.Enabled = false;
ComboCategoria.SelectedItem = CategoriaYPresentaciones.Categoria.fromid(productos.Categoria_ID).Nombre;
}
This code is in charge of filling all the fields of my form as such, but I have two textboxes that, when the EditValueChanged event is executed, make a calculation, how can I prevent this event from happening until the form is filled with the data from the database data and user make the changes?
This is the textbox code:
private void precio1frm_EditValueChanged(object sender, EventArgs e)
{
decimal beneficio = (precio1frm.Value - Costo.Value);
beneficio1frm.Value = (beneficio / Costo.Value) * 100;
}

You are not showing where you define the event handler, so I assume you are letting the designer do this via the Windows Forms IDE. So if you look at events for your textbox in designer, you see it there.
What that does, is create this code (or similar):
precio1frm.EditValueChanged += precio1frm_EditValueChanged;
Find that code (if not sure where it is, right-click the definition for precio1frm_EditValueChanged and choose 'Find all References' or click on the 'references' link just above it. Cut it from there and paste it at the end of your Form Load code. Repeat for each of the controls as required.
That means the event handler won't be fired until after form load is complete

Related

Button click event not responding c#

The problem we are having is accessing the click event for a button which is created in the click event of another button i.e. clicking the first button generates a new panel and controls, and we now want the button on this newly created panel to perform an action.
The controls have been declared at the top of the class as follows:
Panel createElementPage = null;
TextBox elementDescription = null;
TextBox elementName = null;
Button continueButton = null;
AuditSystem audit;
Here is an excerpt of the method that generates the new panel, the part that defines the continueButton is written as follows:
public void CE_Click(object sender, EventArgs e)
{
createElementPage.Controls.Add(elementDescription);
continueButton = new Button();
continueButton.Text = "Continue";
continueButton.Location = new Point(700, 500);
continueButton.Size = new Size(100, 50);
createElementPage.Controls.Add(continueButton);
}
We want to access the continueButton's click event handler but the method we have written does not seem to be working. This is what we have so far:
private void continueButton_Click(object sender, EventArgs e)
{
Console.WriteLine(" something");
}
Clicking the button yields no results, and we have tried a few solutions such as implementing a seperate eventHandler method. Does anybody have a fix for this?
You have to actually subscribe to the event:
continueButton.Click += continueButton_Click;
Events need to be told what they should handle. Without that, they won't "listen" to anything.
Friendly note: be careful when adding handlers "on demand" like this (i.e. outside of the designer). It doesn't really apply here (you have a new button each time), but it's fairly easy to accidentally subscribe to a control's event multiple times, and your handler will fire multiple times as a result. It's just nice to be aware of :)

Text not showing in a label when clicking on a button

I am having trouble with a project I am working on that involves clicking on a button, and text is supposed to show up in a label box I created. I know this would be easier using a text box to show the text when I click on the button but my instructor wants us to use a label instead to show the text. I have debugged the project and everything says it is fine, but when I click on one of my buttons at the bottom, the text does not show up in the assigned label. Below is the code I am using. Maybe I am missing something. For example, when I click on customer relations button, it should show the department in one label, the contact name in the next, and the phone number in the next. I hope that is enough information
private void btnCustomerRelations_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Customer Relations";
lblContact.Text = "Tricia Smith";
lblPhone.Text = "500-1111";
}
private void btnMarketing_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Marketing";
lblContact.Text = "Michelle Tyler";
lblPhone.Text = "500-2222";
}
private void btnOrderProcessing_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Order Processing";
lblContact.Text = "Kenna Ross";
lblPhone.Text = "500-3333";
}
private void btnShipping_Click(object sender, EventArgs e)
{
lblDepartment.Text = "Shipping";
lblContact.Text = "Eric Johnson";
lblPhone.Text = "500-4444";
}
Did the project compiled without any errors ?.
By default every Event Handler in C# is declared as void,which I am unable to find in your code.Did you modify the Event Handlers generated by Visual Studio,if this is the case then the issue you are facing is because of this.
Let me explain what would have gone wrong;
Whenever you create a Event Handler for any control using the Properties Window of Visual Studio,for the sake of this explanation let me take example of TextBox.Suppose you have a TextBox (named as textBox1,which is default) and you subscribe to its TextChanged Event (to do that locate TextChanged event in the events window of Visual Studio and double click it,when you do that Visual Studio generates this for you;
private void textBox1_TextChanged(object sender,EventArgs e)
{
}
This is what we programmers call an Event Handler,now locate Solution Explorer Window in Visual Studio click on Form1.Designer.cs you will get a lot of code there,locate the line which says
private System.Windows.Forms.TextBox textBox1;
where textBox1 is the control's name.Locate a plus sign above this point,click it and locate the following code;
//
// textBox1
//
this.textBox1.AcceptsReturn = true;
this.textBox1.Location = new System.Drawing.Point(478, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(359, 23);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
PS:The Location , AcceptsReturn , Size and TabIndex property in yours might not be same as mine.
Read the last line of this code,it says;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
where textBox1_TextChanged is the name of event which must be same as that defined in Form1.cs.If you modify this you'll get various compile time errors.
So now I guess you know what is the relationship between Form1.cs(main code file) and Form1.Designer.cs(code behind file).
In one line the conclusion is that make sure ;
Any event handler function in Form1.cs starts with private void ....,and the words after private void are exactly same as defined in the code behind file for that particular control.If you would like to read more about this stuff,have a look here.
Hope it would have helped you to solve the issue.Anything else left please inform me.
Have you tried inserting an Application.DoEvents() statement at the end of each method? Sometimes forms are finicky about updating labels and that method will force the form to redraw itself.

Find Control in collection - event ControlAvailable Disabled

In my lightswitch app i need to add a small image control to every row, when clicking on it , it should send you to a detail screen. I made the silverlight control and added it to the lightswitch app.
partial void VidContentItemRessources_Loaded(bool succeeded) {
int index = 0;
foreach (VidContentItemRessourcesItem cust in this.VidContentItemRessources) {
this.FindControlInCollection("ImageLinkIcon", this.VidContentItemRessources.ElementAt(index))
.ControlAvailable += (s, e) => {
MyLinkImage = (e.Control as LinkImage);
MyLinkImage.MouseLeftButtonDown += MyLinkImage_MouseLeftButtonDown;
};
index++;
}
}
But if i do this i get an error that the event control available can't be used on controls in collection ..
So i tried to do it like this
LinkImage neco = this.FindControlInCollection("ImageLinkIcon", this.VidContentItemRessources.ElementAt(index)) as LinkImage;
neco.MouseLeftButtonDown += MyLinkImage_MouseLeftButtonDown;
But then neco is allways null because it is trying to load the control before it's available... any solution pls ?
These types of initialisations should go in the screen's Created method, that way you're guaranteed that all of the controls on the screen have been created. If any of the screen's methods (like InitializeDataWorkspace, Created, Saving etc) aren't in your code file, you can create them by using the Write Code dropdown box in the screen editor.
I solved it like this:
I catching click event in silverlight control than i invoking method in lightsiwtch
public void MouseClick(object sender, MouseButtonEventArgs e) {
var objDataContext = (IContentItem)this.DataContext;
var Screen = (Microsoft.LightSwitch.Client.IScreenObject)objDataContext.Screen;
Screen.Details.Dispatcher.BeginInvoke(() => {
Screen.Details.Methods["DoImageLinkEvent"]
.CreateInvocation(null).Execute();
});
}

BUG: Can't choose dates on a DatePicker that fall outside a floating VSTO Add-In

I logged the issue with Microsoft here - the Repro is available for download: https://connect.microsoft.com/VisualStudio/feedback/details/741454/value-change-event-doesnt-fire-for-datetimepicker-controls-used-in-vsto-add-ins
If you put a DateTimePicker in a Excel VSTO floating Add-In and position it so when the calendar drops down, it is outside the edge of the add-in, see here:
Choosing any of the dates circled in the green works as expected, but when clicking any dates circled in red, it just closes the calendar drop down and doesn't set the date!
Does anyone know how I can fix this?
Edit
This SO user has experienced the problem using WPF:
VSTO WPF ContextMenu.MenuItem Click outside a TaskPane not raised
The answer to that question shows the issue was reported to connect a while back but still no solution with VSTO 4.0 SP1: https://connect.microsoft.com/VisualStudio/feedback/details/432998/excel-2007-vsto-custom-task-pane-with-wpf-context-menu-has-focus-problems
One of the workarounds is to use the DispatcherFrame to pump messages and subscribe to GotFocusEvent and LostFocusEvent for the menu. http://blogs.msdn.com/b/vsod/archive/2009/12/16/excel-2007-wpf-events-are-not-fired-for-items-that-overlap-excel-ui-for-wpf-context-menus.aspx but this is all WPF code for menu's not a solution for Winform DateTimePicker.
Repro for Microsoft Connect:
New Project > Excel 2010 Add-In
using TaskPane;
using Microsoft.Office.Core;
namespace ExcelAddIn2
{
public partial class ThisAddIn
{
TaskPaneView MyTaskView = null;
Microsoft.Office.Tools.CustomTaskPane MyTaskPane = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//setup custom taskpane
MyTaskView = new TaskPaneView();
MyTaskView.currentInstance = Globals.ThisAddIn.Application;
MyTaskPane = this.CustomTaskPanes.Add(MyTaskView, "MyTaskView");
MyTaskPane.DockPosition = Microsoft.Office.Core.MsoCTPDockPosition.msoCTPDockPositionFloating;
MyTaskPane.DockPositionRestrict = MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoChange;
MyTaskPane.Visible = true;
}
}
File Menu > Add > New Project > Class Library > named TaskPane
Then in the TaskPane project create a User Control called TaskPaneView
public partial class TaskPaneView : UserControl
{
public TaskPaneView()
{
InitializeComponent();
}
public Microsoft.Office.Interop.Excel.Application currentInstance { get; set; }
public TaskPaneCtrl getTaskPaneCtrl
{
get { return this.taskPaneCtrl1; }
}
}
Next create a User Control with a DateTimePicker, make sure the Calendar control is located toward the bottom right of the user control
public partial class TaskPaneCtrl : UserControl
{
public TaskPaneCtrl()
{
InitializeComponent();
}
}
In the TaskPane class library Reference the Excel Interop (eg c:\Program Files x86\Microsoft Visual Studio 14.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Excel.dll).
Build the solution. Commenting out parts that dont work. Build Solution.
Now drag and drop the TaskPaneCtrl onto the TaskPaneView and uncomment thing that failed to compile.
F5 and click the Calendar Control, now try to select a date that is outside the taskpane area. No Value Change event fires, it behaves like a click outside the calendar!
Note: I tried a drop downlist that falls off the control but its events DO FIRE!
"Floating" is the key to the problem here. What's never not a problem (occasionally responsible for odd things) is relying on the message pump in Excel to dispatch Windows messages, the messages that make these controls respond to input. This goes wrong in WPF as much as Winforms, they have their own dispatch loop that filters messages before they are delivered to the window. Key things that go wrong when their respective dispatcher isn't used are stuff like tabbing and short-cut keystrokes.
And then some, this kind of problem would be induced by Excel doing its own filtering before dispatching messages. I'd guess at an anti-malware feature, Microsoft is forever worried about programs messing with Office apps.
The Winforms solution is the same one as the WPF workaround, you need to pump your own message loop. That requires some surgery, DateTimePicker isn't going to cooperate since it doesn't allow its DropDown event to be cancelled and it is raised after the calendar is already shown. The workaround is silly but effective, add a button to your form that looks just like the dropdown arrow on the DTP and make it overlap the arrow so it gets clicked instead of the arrow.
Some example code for getting the button to overlap the dropdown arrow:
public Form1() {
InitializeComponent();
var btn = new Button();
btn.BackgroundImage = Properties.Resources.DropdownArrow;
btn.FlatStyle = FlatStyle.Flat;
btn.BackColor = Color.FromKnownColor(KnownColor.Window);
btn.Parent = dateTimePicker1;
btn.Dock = DockStyle.Right;
btn.Click += showMonthCalendar;
dateTimePicker1.Resize += delegate {
btn.Width = btn.Height = dateTimePicker1.ClientSize.Height;
};
}
The Click event handler needs to show a dialog that contains a MonthCalendar:
private void showMonthCalendar(object sender, EventArgs e) {
dateTimePicker1.Focus();
using (var dlg = new CalendarForm()) {
dlg.DateSelected += new DateRangeEventHandler((s, ea) => dateTimePicker1.Value = ea.Start);
dlg.Location = dateTimePicker1.PointToScreen(new Point(0, dateTimePicker1.Height));
dlg.ShowDialog(this);
}
}
With CalendarForm a form you add that's borderless and contains just a MonthCalendar:
public partial class CalendarForm : Form {
public event DateRangeEventHandler DateSelected;
public CalendarForm() {
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
monthCalendar1.Resize += delegate {
this.ClientSize = monthCalendar1.Size;
};
monthCalendar1.DateSelected += monthCalendar1_DateSelected;
}
void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e) {
if (DateSelected != null) DateSelected(this, e);
this.DialogResult = DialogResult.OK;
}
}
speculation:
The bug occurs because the datetimepicker's surface is not rendered until after the click message is sent.
Next steps to Answer:
If available try testing with some 3rd party date time picker controls.
I realise this isn't a complete answer since I don't know yet whether it will fix your problem.
Other possible answer:
Resize the taskpane to fit the control. This will sort out the bug, but look a bit weird from a user point of view.

C# asp.net Button_Click event handler not working

I have a webusercontrol with a few controls on it like some labels,a textbox and eventually a button. The purpose of this control is to add it to my main page in a placeholder every time I click on the button on the webusercontrol.
This is the code behind my button on my webcontrol
protected void btnCriteriaToevoegen_Click(object sender, EventArgs e)
{
//New eventhandler == all of the eventhandlers of all the objects who have subscribed to the event.
EventHandler eventhandler = ButtonDoorgaan;
ButtonOpslaanEvent mijnevent = new ButtonOpslaanEvent();
//Basic variables I will give with my costum event(ButtonOpslaanEvent)
mijnevent.Naam = txtCriteriumNaam.Text;
mijnevent.Score = Convert.ToInt16(DdlCriteriumScoreSchaal.SelectedValue);
int weging = Convert.ToInt16(DdlCriteriumWeging.SelectedValue) - 1;
mijnevent.Weging = Convert.ToInt16(weging);
//If the eventhandler is not null, for every object that has an eventhandler, execute it.
if(eventhandler!=null)
eventhandler(sender, mijnevent);
}
The eventhandler that need to be executed when the event is fired is defined in my main page like this :
private void critlijn_ButtonDoorgaan(object sender, EventArgs e)
{
ButtonOpslaanEvent eigenevent = (ButtonOpslaanEvent)e;
IEnumerator<Domein> domeinenumerator = domeinen.GetEnumerator();
while (domeinenumerator.MoveNext())
{
if (domeinenumerator.Current.DomeinNaam.Equals(lijstdomeinitemgeselecteerd))
{
Criterium nieuwcriterium = new Criterium();
nieuwcriterium.CriteriumNaam = eigenevent.Naam;
nieuwcriterium.CriteriumScore = Convert.ToString(eigenevent.Score);
nieuwcriterium.CriteriumWeging = Convert.ToString(eigenevent.Weging);
domeinenumerator.Current.Criteriums.Add(nieuwcriterium);
}
}
btnCriteriaToevoegen_Click(sender, e);
}
The btnCriteriaToevoegen_Click event fires and then calls this method(addCriteriaButton()), which will add the button onto the placeholder in my main page:
private void addCriteriaButton()
{
Criterialijn criterialijn = (Criterialijn)LoadControl("~/Criterialijn.ascx");
//Add eventhandlers to control
criterialijn.ButtonDoorgaan += new EventHandler(critlijn_ButtonDoorgaan);
criterialijn.Aangevinkt += new EventHandler(critlijn_Aangevinkt);
//Every control on the page except this one, not enabled
IEnumerator<Criterialijn> criterialijnenumerator = criteriacontrols.GetEnumerator();
while (criterialijnenumerator.MoveNext())
{
criterialijnenumerator.Current.Enabled = false;
}
//Add it to a list of webusercontrols that are currently on screen
criteriacontrols.Add(criterialijn);
criterialijn.Enabled = true;
//Add to placeholder
plhCriteria.Controls.Add(criterialijn);
}
So when all this is said and done, and I run my program, he adds the control to my placeholder, but when I click on the button, he does not add a new control to my placeholder, and just clears my placeholder for some reason. Normally everything should be fine, but I have tried to see if he actually fires the event when you click on the button, and he does not. I have tried to give you a sample of my code, because the code of the whole page is quite big and that would not help you at all. Any ideas why he is not firing the event of the button?
So when your button that you dynamically added posts back, a new page instance is created and that button no longer exists (since you only added it on the previous button click), it has not been recreated.
You must re-create dynamic controls on each postback
Remeber, a new instance of the Page class is created for each postback, any previously created controls, event handlers will not exists in the new instance unless you explicitly re-create them.
I assume these Criteria are some sort of tree structure the user can navigate through (and hopefully arriving at the end somewhere ?).
About btnCriteriaToevoegen_Click:
Why are you defining an event inside a method?
In critlijn_ButtonDoorgaan and addCriteriaButton:
Instead of using an enumerator, just use
foreach(var control in criteriacontrols)
control.Enabled = false;
So yeah, fair to say it's still not quite comprehensable, but it least I tried right? :)
EDIT
ok, then I have this question:
The eventhandler that need to be
executed when the event is fired is
defined in my main page like this :
How sure are you that, when you do
EventHandler eventhandler = ButtonDoorgaan;
the variable "eventhandler" gets all eventhandlers attached to ButtonDoorgaan ?
EDIT 2 (the return)
See Richard Friend's answer; your control is not there anymore

Categories

Resources