I can't run my code because there is a error saying:
Cannot assign to 'OnNewLand' because it is a 'method group
This is strange because I have used the same structure as my other methods and there were no problem with them.
Here is my code.
private void CreateNewFlight()
{
string flightCode = ReadFlightCode();
//Create the new bidder
if (!string.IsNullOrEmpty(flightCode))
{
FlightWindow frm = new FlightWindow(Flightcode.Text);
frm.Show();
//Subscribe to the publisher's new bid and quit bid events
frm.NewStart += OnNewStartClick;
frm.NewChangeRoute += OnNewChangeRoute;
frm.OnNewLand += OnNewLand; <----Here is the error <-------
}
}
Cannot assign to 'OnNewLand' because it is a 'method group
My other window:
public event EventHandler<Start> NewStart;
public event EventHandler<ChangeRoute> NewChangeRoute;
public event EventHandler<Land> NewLand;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Start startinfo = new Start(this.Title);
OnNewStart(startinfo); //Raise event
btnLand.IsEnabled = true;
Routetxt.IsEnabled = true;
changebtn.IsEnabled = true;
btnStart.IsEnabled = false;
}
private void changebtn_Click(object sender, RoutedEventArgs e)
{
ChangeRoute changeinfo = new ChangeRoute(this.Title, Routetxt.Text);
OnNewChangeRoute(changeinfo); //Raise event
}
private void btnLand_Click(object sender, RoutedEventArgs e)
{
Land landinfo = new Land(this.Title);
OnNewLand(landinfo); //Raise event
}
//Raise Event
public void OnNewStart(Start e)
{
if (NewStart != null)
NewStart(this, e);
}
public void OnNewChangeRoute(ChangeRoute e)
{
if (NewChangeRoute != null)
NewChangeRoute(this, e);
}
public void OnNewLand(Land e)
{
if (NewLand != null)
NewLand(this, e);
}
You need
frm.OnNewLand += NewLand;
instead of
frm.OnNewLand += OnNewLand;
You might be interested to know what does it mean by method group. Visit this so thread.
Related
I am running my windows store app and i got error like this.
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code
WinRT information: Only one handler for the PrintTaskRequested event may be registered at a time.
Additional information: A method was called at an unexpected time.
My code is here.help me to get understand the problem and resolve this issue.Kindly tell me know the exact problem.
//print sample
protected PrintDocument printDocument = null;
protected IPrintDocumentSource printDocumentSource = null;
internal List<UIElement> printPreviewElements = new List<UIElement>();
protected event EventHandler pagesCreated;
Error came in print task requested handler
protected virtual void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested =>
{
printTask.Completed += async (s, args) =>
{
if (args.Completion == PrintTaskCompletion.Failed)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
MessageDialog dialog = new MessageDialog("Something went wrong while trying to print. Please try again.");
await dialog.ShowAsync();
});
}
};
sourceRequested.SetSource(printDocumentSource);
});
}
protected virtual void RegisterForPrinting()
{
printDocument = new PrintDocument();
printDocumentSource = printDocument.DocumentSource;
printDocument.Paginate += CreatePrintPreviewPages;
printDocument.GetPreviewPage += GetPrintPreviewPage;
printDocument.AddPages += AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested += PrintTaskRequested;
}
protected virtual void UnregisterForPrinting()
{
if (printDocument != null)
{
printDocument.Paginate -= CreatePrintPreviewPages;
printDocument.GetPreviewPage -= GetPrintPreviewPage;
printDocument.AddPages -= AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= PrintTaskRequested;
}
}
protected virtual void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
{
printPreviewElements.Clear();
PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
AddOnePrintPreviewPage(pageDescription);
if (pagesCreated != null)
{
pagesCreated.Invoke(printPreviewElements, null);
}
((PrintDocument)sender).SetPreviewPageCount(printPreviewElements.Count, PreviewPageCountType.Intermediate);
}
protected virtual void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
{
((PrintDocument)sender).SetPreviewPage(e.PageNumber, printPreviewElements[e.PageNumber - 1]);
}
protected virtual void AddPrintPages(object sender, AddPagesEventArgs e)
{
foreach (UIElement element in printPreviewElements)
{
printDocument.AddPage(element);
}
((PrintDocument)sender).AddPagesComplete();
}
protected virtual void AddOnePrintPreviewPage(PrintPageDescription printPageDescription)
{
TextBlock block = new TextBlock();
block.Text = "This is an example.";
block.Width = printPageDescription.PageSize.Width;
block.Height = printPageDescription.PageSize.Height;
printPreviewElements.Add(block);
}
//protected override void OnNavigatedTo(NavigationEventArgs e)
//{
// RegisterForPrinting();
//}
//protected override void OnNavigatedFrom(NavigationEventArgs e)
//{
// UnregisterForPrinting();
//}
private void printBirth_Click(object sender, RoutedEventArgs e)
{
RegisterForPrinting();
}
you can use it
private async void printBirth_Click(object sender, RoutedEventArgs e)
{
await Windows.Graphics.Printing.PrintManager.showPrintUIAsync()
}
I would like to create custom Eventargs for a series of events. I am using a third party X/Y scope where I plot Strength vs frequency. This scope has the ability to place "Markers" on it which are just little triangles at various frequencies. These markers support events such as when the mouse enters the marker, a click is performed, and the mouse leaves the marker. So for two markers, here is the code:
private void createEvents()
{
this.scope2.MarkerGroups[0].Click += new EventHandler(Marker0_Click);
this.scope2.MarkerGroups[0].MouseEnter += new EventHandler(Marker0_Enter);
this.scope2.MarkerGroups[0].MouseLeave += new EventHandler(Marker0_Leave);
this.scope2.MarkerGroups[1].Click += new EventHandler(Marker1_Click);
this.scope2.MarkerGroups[1].MouseEnter += new EventHandler(Marker1_Enter);
this.scope2.MarkerGroups[1].MouseLeave += new EventHandler(Marker1_Leave);
}
// And now the event handlers
private void Marker0_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker0_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker0_Leave(object sender, EventArgs e)
{
// do something
}
private void Marker1_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker1_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker1_Leave(object sender, EventArgs e)
{
// do something
}
Now this is fine for two markers....but I need 80 of them. I could just write the whole thing out but there has to be a better way. So I started like this:
private void createMarkerEvents()
{
for (int i = 0; i < 80; i++)
{
this.scope2.MarkerGroups[i].Click += new EventHandler(Marker_Click);
this.scope2.MarkerGroups[i].MouseEnter += new EventHandler(Marker_Enter);
this.scope2.MarkerGroups[i].MouseLeave += new EventHandler(Marker_Leave);
}
}
private void Marker_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker_Leave(object sender, EventArgs e)
{
// do something
}
So the question is how can I pass the actual marker number from the events to the event handlers?
There has got to be a way.
Thanks, Tom
If you want to identify marker group you may cast object sender to a MarkerGroup object
private void AnyMarker_Click(object sender, EventArgs e)
{
MarkerGroup group = (MarkerGroup)sender;
int indexOfMarkerGroup = this.scope2.MarkerGroups.IndexOf(group);
//do something;
}
OFF: You should define a custom EventArgs class:
public class MyEventArgs : EventArgs
{
public int MyCustomProperty {get;set;}
}
Then use it in your event:
public event EventHandler<MyEventArgs> ButtonPressed;
Fire event using custom args:
if(ButtonPressed != null)
{
ButtonPressed(this, new MyEventArgs { MyCustomProperty = 1 });
}
EDIT
Full example:
private void createMarkerEvents()
{
for (int i = 0; i < 80; i++)
{
this.scope2.MarkerGroups[i].Click += new EventHandler(Marker_Click);
this.scope2.MarkerGroups[i].MouseEnter += new EventHandler(Marker_Enter);
this.scope2.MarkerGroups[i].MouseLeave += new EventHandler(Marker_Leave);
}
}
private void Marker_Click(object sender, EventArgs e)
{
// When markergroup fires and event, it passes reference to itself as `sender` parameter
// so we can get access it
MarkerGroup mg = (MarkerGroup)sender; // this marker has fired a click event
// Now you know which marker has fired event
// if you want to determine it's index in MarkerGroups collection:
int index = this.scope2.MarkerGroup.IndexOf(mg);
// now you know MarkerGroup and it's index
}
private void Marker_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker_Leave(object sender, EventArgs e)
{
// do something
}
I have the following scenario: My application has a compiler that works correctly. The user chooses a control on the screen and write code in C # for this control. Before recording in the database, the user has the option to want if this event occurs before the code already written for the control or if the code you have written will have priority over the system code. My actual code:
public void ExecutaCodigo (string codigo)
{
ExecuteSnippetUser(codigo);
}
public void AtribuiEvento(Control c, string evento, string codigo, bool prioritario)
{
evento = evento.ToLower();
if(evento == "click")
{
if (!prioritario)
{
c.Click += delegate(Object sender, EventArgs e)
{
ExecuteSnippetUser(codigo);
// works fine!!! application and after, user code
};
}
else
{
c.Click -= delegate(Object sender, EventArgs e)
{
};
c.Click += delegate(Object sender, EventArgs e)
{
ExecuteSnippetUser(codigo);
};
}
}
}
What am I doing wrong ?
You'll have to hold onto a reference to the handler that you used to be able to remove it:
private ClickEventHandler handler;
public void AtribuiEvento(Control c, string evento, string codigo, bool prioritario)
{
evento = evento.ToLower();
if(evento == "click")
{
c.Click -= handler;
handler = delegate(Object sender, EventArgs e)
{
ExecuteSnippetUser(codigo);
};
c.Click += handler;
}
}
This question already has answers here:
Pass extra parameters to an event handler?
(10 answers)
Closed 9 years ago.
i want to pass my List<string> as parameter using my event
public event EventHandler _newFileEventHandler;
List<string> _filesList = new List<string>();
public void startListener(string directoryPath)
{
FileSystemWatcher watcher = new FileSystemWatcher(directoryPath);
_filesList = new List<string>();
_timer = new System.Timers.Timer(5000);
watcher.Filter = "*.pcap";
watcher.Created += watcher_Created;
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectories = true;
}
void watcher_Created(object sender, FileSystemEventArgs e)
{
_timer.Elapsed += new ElapsedEventHandler(myEvent);
_timer.Enabled = true;
_filesList.Add(e.FullPath);
_fileToAdd = e.FullPath;
}
private void myEvent(object sender, ElapsedEventArgs e)
{
_newFileEventHandler(_filesList, EventArgs.Empty);;
}
and from my main form i want to get this List:
void listener_newFileEventHandler(object sender, EventArgs e)
{
}
Make a new EventArgs class such as:
public class ListEventArgs : EventArgs
{
public List<string> Data { get; set; }
public ListEventArgs(List<string> data)
{
Data = data;
}
}
And make your event as this:
public event EventHandler<ListEventArgs> NewFileAdded;
Add a firing method:
protected void OnNewFileAdded(List<string> data)
{
var localCopy = NewFileAdded;
if (localCopy != null)
{
localCopy(this, new ListEventArgs(data));
}
}
And when you want to handle this event:
myObj.NewFileAdded += new EventHandler<ListEventArgs>(myObj_NewFileAdded);
The handler method would appear like this:
public void myObj_NewFileAdded(object sender, ListEventArgs e)
{
// Do what you want with e.Data (It is a List of string)
}
You can define the signature of the event to be whatever you want. If the only information the event needs to provide is that list, then just pass that list:
public event Action<List<string>> MyEvent;
private void Foo()
{
MyEvent(new List<string>(){"a", "b", "c"});
}
Then when subscribing to the event:
public void MyEventHandler(List<string> list)
{
//...
}
How do I prevent firing CheckedChanged event when checking a control programmatically?
I usually do this the following way.
private bool isFrozen = false;
private void btn1_CheckedChanged(object sender, EventArgs e)
{
if (isFrozen)
return;
isFrozen = true;
btn2.Checked = false;
isFrozen = false;
// Do some stuff
}
private void btn2_CheckedChanged(object sender, EventArgs e)
{
if (isFrozen)
return;
isFrozen = true;
btn1.Checked = false;
isFrozen = false;
// Do another stuff
}
Is there a better or more common solution?
I think your way is fine.
The other way to do it is remove the EventHandler before the check, and then add it back again after the check. This way eliminates the need for the isFrozen variable.
private void btn1_CheckedChanged(object sender, EventArgs e)
{
btn2.CheckedChanged -= btn2_CheckedChanged;
btn2.Checked = false;
btn2.CheckedChanged += btn2_CheckedChanged;
// Do some staff
}
private void btn2_CheckedChanged(object sender, EventArgs e)
{
btn1.CheckedChanged -= btn1_CheckedChanged;
btn1.Checked = false;
btn1.CheckedChanged += btn1_CheckedChanged;
// Do another staff
}
In VB:
RemoveHandler btn2.CheckedChanged, AddressOf btn2_CheckedChanged
btn2.Checked = false
AddHandler btn2.CheckedChanged, AddressOf btn2_CheckedChanged
I came across this post after wanting to implement something like this for a while. I regularly use Measurement Studio from National Instruments, and their WinForms controls that have the event StateChanging or StateChanged pass a parameter of type ActionEventArgs, which has a property Action which can take three values: ByKeyboard, ByMouse and Programatic. This is very useful in determining what has caused the state of the control to change. I wanted to replicate this in a standard WinForms checkbox.
Here is my code:
public enum ControlSource
{
Programatic,
ByKeyboard,
ByMouse
}
public class AwareCheckBox : Checkbox
{
public AwareCheckBox()
: base()
{
this.MouseDown += AwareCheckbox_MouseDown;
this.KeyDown += AwareCheckbox_KeyDown;
}
private ControlSource controlSource = ControlSource.Programatic;
void AwareCheckbox_KeyDown(object sender, KeyEventArgs e)
{
controlSource = ControlSource.ByKeyboard;
}
void AwareCheckbox_MouseDown(object sender, MouseEventArgs e)
{
controlSource = ControlSource.ByMouse;
}
public new event AwareControlEventHandler CheckedChanged;
protected override void OnCheckedChanged(EventArgs e)
{
var handler = CheckedChanged;
if (handler != null)
handler(this, new AwareControlEventArgs(controlSource));
controlSource = ControlSource.Programatic;
}
}
public delegate void AwareControlEventHandler(object source, AwareControlEventArgs e);
public class AwareControlEventArgs : EventArgs
{
public ControlSource Source { get; private set; }
public AwareControlEventArgs(ControlSource s)
{
Source = s;
}
}
I'm sure there are improvements to make, but my rudimentary testing has demonstrated that it works. I have posted here simply in case others stumble across this issue and want a clearer way of distinguishing where the change was initiated. Any comments welcome.
Just have a counter value set and check for the value in the beginning of the event. It solved my problem in 10 minutes. I am using 5 slide buttons in Xamarin to make it as a radio button.
private void testtoggle1(object sender, ToggledEventArgs e)
{
if (chk_ctr == 1) { return; }
chk_ctr = 1;
sw2.IsToggled= false;
sw3.IsToggled = false;
sw4.IsToggled = false;
sw5.IsToggled = false;
chk_ctr = 0;
}
private void testtoggle2(object sender, ToggledEventArgs e)
{
if (chk_ctr == 1) { return; }
chk_ctr = 1;
sw1.IsToggled = false;
sw3.IsToggled = false;
sw4.IsToggled = false;
sw5.IsToggled = false;
chk_ctr = 0;
}
private void testtoggle3(object sender, ToggledEventArgs e)
{
if (chk_ctr == 1) { return; }
chk_ctr = 1;
sw1.IsToggled = false;
sw2.IsToggled = false;
sw4.IsToggled = false;
sw5.IsToggled = false;
chk_ctr = 0;
}
private void testtoggle4(object sender, ToggledEventArgs e)
{
if (chk_ctr == 1) { return; }
chk_ctr = 1;
sw1.IsToggled = false;
sw2.IsToggled = false;
sw3.IsToggled = false;
sw5.IsToggled = false;
chk_ctr = 0;
}
private void testtoggle5(object sender, ToggledEventArgs e)
{
if (chk_ctr == 1) { return; }
chk_ctr = 1;
sw1.IsToggled = false;
sw2.IsToggled = false;
sw3.IsToggled = false;
sw4.IsToggled = false;
chk_ctr = 0;
}