|
Hello. New to C# so experimenting. Previous language VBA, where I used Application.EnableEvents to turn event handling on and off. Realise that's pretty sledgehammer.
Discovered this, which has as yet unfamiliar syntax, but works:
kiloTextBox.TextChanged -= kiloTextBox_TextChanged;
What would I write if I was looping through an array of text boxes textBoxes [i] to turn all their event handlers on and off?
Can it be done that way?
Could someone explain the syntax?
Thanks for your time.
Pogoodill
|
|
|
|
|
It's exactly the same syntax: the "-=" removes a specific event handler from the chain of handlers for each event.
To explain that, assume you have a class with an Event:
public class MyClass
{
public event EventHandler TestEvent;
protected virtual void OnTestEvent(EventArgs e)
{
EventHandler eh = TestEvent;
if (eh != null)
{
eh(this, e);
}
}
public void Signal()
{
OnTestEvent(null);
}
} And that you create an instance, and attach two handlers to the event, and raise teh event:
void mc_TestEvent1(object sender, EventArgs e)
{
Console.WriteLine("Event handler 1");
}
void mc_TestEvent2(object sender, EventArgs e)
{
Console.WriteLine("Event handler 2");
}
private void MyButton_Click(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.TestEvent += mc_TestEvent1;
mc.TestEvent += mc_TestEvent2;
mc.Signal();
} You will get this output:
Event handler 1
Event handler 2 Because event handlers are "chained" - all handlers attached to the event for that specific instance will get fired.
So this code:
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
mc1.TestEvent += mc_TestEvent1;
mc2.TestEvent += mc_TestEvent2;
mc1.Signal(); Will only output one line:
Event handler 1 Because only one event handler is attached for each instance. To get the output
Event handler 1
Event handler 2 You would have to call Signal on both instances:
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
mc1.TestEvent += mc_TestEvent1;
mc2.TestEvent += mc_TestEvent2;
mc1.Signal();
mc2.Signal(); the "-=" syntax removes an event handler:
MyClass mc = new MyClass();
mc.TestEvent += mc_TestEvent1;
mc.TestEvent += mc_TestEvent2;
Console.WriteLine("Two:");
mc.Signal();
mc.TestEvent -= mc_TestEvent1;
Console.WriteLine("One:");
mc.Signal();
Gives you:
Two:
Event handler 1
Event handler 2
One:
Event handler 2
So, if you have a collection of MyClass objects, you can remove the handler inside the loop using exactly the same syntax:
foreach (MyClass mc in myClassesCollection)
{
mc.TestEvent -= mc_TestEvent1;
}
Note that this doesn't "turn the events off" it just removes a specific handler method from the instance (which probably as far as you care, turns it off!)
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thanks so much for the detailed explanation of the syntax. Very much appreciated. I understand most of it. However, as far as I can see, the example will work when each event handler is called the same, eg.
textBoxes[i].TextChanged-= anEventHandlerWithGenericName_TextChanged
but my event handlers are called different things, based on their objects' names:
kiloTextBox.TextChanged -= kiloTextBox_TextChanged
poundTextBox.TextChanged -= poundTextBox_TextChanged
stoneTextBox.TextChanged -= stoneTextBox_TextChanged
My naive, straw-clutching attempt was...
textBoxes[i].TextChanged-= textBoxes[i] + "_TextChanged"
... which obviously didn't work. How do I reference all of the event handlers using my looping variable [i]?
Thanks again for your time.
|
|
|
|
|
You can't specify wild cards for removing event handlers, and while it can be done, it gets complicated! Reflection is the answer here...
static void RemoveEvents(object o, string nameOfEvent)
{
FieldInfo fi = o.GetType().GetField(nameOfEvent, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic);
if (fi != null)
{
fi.SetValue(o, null);
}
}
private void MyButton_Click(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.TestEvent += mc_TestEvent1;
mc.TestEvent += mc_TestEvent2;
Console.WriteLine("Two:");
mc.Signal();
RemoveEvents(mc, "TestEvent");
Console.WriteLine("None:");
mc.Signal();
}
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thanks again! Plenty for me to chew on there. I've only been at it for a couple of weeks so will take a little time to sink in.
Really appreciate your help.
|
|
|
|
|
OriginalGriff has given you the "grand tour" of EventHandlers here; I hope I can add another perspective:
1. the "head 'em off at the pass" stratagem: if you don;t want the TextBoxes to raise the Event, consider setting their 'Enabled property to 'false, or their locked Property to 'true.
or ... if you want the user to enter edit text, but, not raise the event:
2. the sub-class stratagem: you inject an action into the instances of the sub-classed TextBox; whether that action is executed is controlled by a boolean flag
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace YourNameSpace
{
public partial class TextBoxEXEvents : TextBox
{
public TextBoxEXEvents()
{
InitializeComponent();
}
public Action<string, string> TextChangedAction { set; get; }
public bool IsTextChangedEnabled = true;
public TextBoxEXEvents(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private void TextBoxEXEvents_TextChanged(object sender, EventArgs e)
{
if (IsTextChangedEnabled && TextChangedAction != null) TextChangedAction(this.Text, this.Name);
}
}
} Here's an example of how this can be used:
private List<TextBoxEXEvents> TBxExInUse;
private void TextChangedAction(string text, string name = "")
{
Console.WriteLine($"text: {text} in: {name}");
}
TBxExInUse = this.Controls.OfType<TextBoxEXEvents>().ToList();
foreach (var tbxex in TBxExInUse)
{
tbxex.TextChangedAction = TextChangedAction;
}
foreach (var tbxex in TBxExInUse)
{
tbxex.IsTextChangedEnabled = YourBooleanValue;
}
«... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12
|
|
|
|
|
Sometimes, instead of "wiring" and "unwiring", it's easier just to test a "flag" in the "wired" event handler as to whether to "execute" or not.
All the text boxes can be wired to the same hander; you can test for which textbox in the handler via the sender object(s) and arguments.
(And improper "wiring" / unwiring can result in memory leaks; duplicate event firings).
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
I have a specific problem I've been trying to solve, and I think I have the right pieces - I'm just putting them together incorrectly. It might be more of a math question than a coding one.
So basically what I want to be able to do is find where "now" is within an arbitrary recurring time period (say, 43 minutes), given a known DateTime that this period recurred. So you have an anchor point, and from that anchor point, you know that every 43 minutes this period starts over, where is "now" in the current period?
I'm sure it involves division and/or modulo, and likely a subtraction using the anchor...so I've been toying with this code, but it isn't giving me the results I'm looking for:
using System;
public class Program
{
public static void Main()
{
TimeSpan interval = new TimeSpan(0, 43, 0);
DateTime anchor = new DateTime(2018, 1, 5, 7, 0, 49);
DateTime now = DateTime.Now;
TimeSpan left = new TimeSpan((now - anchor).Ticks % interval.Ticks);
Console.WriteLine(left);
}
}
Can someone tell me the piece I'm missing here? I'm not entirely sure what mathematical operations DateTime supports, or which ones I should be using in this instance.
Thanks.
|
|
|
|
|
Try it like this :
public static void Main()
{
TimeSpan interval = new TimeSpan(0, 43, 0);
DateTime anchor = new DateTime(2018, 1, 5, 7, 0, 49);
TimeSpan left = new TimeSpan((DateTime.Now - anchor).Ticks % interval.Ticks);
Console.WriteLine(left.toString);
}
... but realize that you get no repeating value - you have to restart it again and again to see new values ...
|
|
|
|
|
I think the confusion is due to the inclusion of "Ticks", when your basic unit is "minutes" (in this case).
Makes no sense to go "smaller" than your smallest sample rate.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
suppose i have a order and order detail entity class in code. i want to fetch specific order data and its related order detail by EF.
can i use this LINQ query
IEnumerable<Order> order= _ctx.order
.Include(x => x.orderdetails)
.Where(x => x.OrderID== _OrderID).ToList();
does the above code works fine? also tell me how to achieve the same with join also?
how to fetch data for selected fields ?
also tell me if i need to show specific customer data and customer order and order details then how i need to compose my EF query? help me with code. thanks
|
|
|
|
|
Your example should should theoretically work. Here's an example using join with syntax-based query in EF:
var order = (from o in _ctx.order
join od in _ctx.orderdetails on o.OrderID equals od.OrderID
where o.OrderID == _OrderID).ToList();
To select specific fields, you could either use an anonymous type object like this:
var order = _ctx.order
.Include(x => x.orderdetails)
.Where(x => x.OrderID== _OrderID)
.Select(x => new
{
OrderID = x.OrderID,
SomeColumn = x.SomeColumn1,
SomeColumn2 = x.SomeColumn1
}).ToList();
Or use a strongly-typed object like this:
var order = _ctx.order
.Include(x => x.orderdetails)
.Where(x => x.OrderID== _OrderID)
.Select(x => new OrderDetail
{
OrderID = x.OrderID,
SomeColumn = x.SomeColumn1,
SomeColumn2 = x.SomeColumn1
}).ToList();
Noticed that the Select clause now use the OrderDetail . The OrderDetail is just a class that holds the properties that you want to use in your query.
For more information and examples on EF, I would recommend you to head over to the official documentation here: Entity Framework | Microsoft Docs[^]
|
|
|
|
|
thanks a lot for your help sir 
|
|
|
|
|
Glad to be of help .
|
|
|
|
|
Hi I am trying to generate petapoco objects in .Net Core class library for MySQL, I have 3 files as
1) Database.tt
2) PetaPoco.Core.ttinclude
3) PetaPoco.Generator.ttinclude
I have changed connection string in Database.tt file, Whenever it trying to save, some error occurs which results in empty Database.cs file.
Here it displays error message like :
Running transformation: System.Runtime.Serialization.SerializationException: Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in Assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable.Server stack trace: at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) at System.Runtime.Serialization.FormatterServices.<>c__DisplayClass9_0.<GetSerializableMembers>b__0(MemberHolder _) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeMessageParts(ArrayList argsToSerialize) at System.Runtime.Remoting.Messaging.SmuggledMethodReturnMessage..ctor(IMethodReturnMessage mrm) at System.Runtime.Remoting.Messaging.SmuggledMethodReturnMessage.SmuggleIfPossible(IMessage msg) at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage& smuggledMrm) at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at EnvDTE._DTE.get_ActiveSolutionProjects() at Microsoft.VisualStudio.TextTemplating8FAECA0C56F72C74151CC9A5C0478EAD855803D5D537389B8623F8D6923181E8F8417EB61C3C9AA7CEE873C74FA7879A4EBD8DE5914CA1814842932C9121F4A5.GeneratedTextTransformation.GetCurrentProject() at Microsoft.VisualStudio.TextTemplating8FAECA0C56F72C74151CC9A5C0478EAD855803D5D537389B8623F8D6923181E8F8417EB61C3C9AA7CEE873C74FA7879A4EBD8DE5914CA1814842932C9121F4A5.GeneratedTextTransformation.GetConnectionString(String& connectionStringName, String& providerName) at Microsoft.VisualStudio.TextTemplating8FAECA0C56F72C74151CC9A5C0478EAD855803D5D537389B8623F8D6923181E8F8417EB61C3C9AA7CEE873C74FA7879A4EBD8DE5914CA1814842932C9121F4A5.GeneratedTextTransformation.InitConnectionString() at Microsoft.VisualStudio.TextTemplating8FAECA0C56F72C74151CC9A5C0478EAD855803D5D537389B8623F8D6923181E8F8417EB61C3C9AA7CEE873C74FA7879A4EBD8DE5914CA1814842932C9121F4A5.GeneratedTextTransformation.LoadTables() at Microsoft.VisualStudio.TextTemplating8FAECA0C56F72C74151CC9A5C0478EAD855803D5D537389B8623F8D6923181E8F8417EB61C3C9AA7CEE873C74FA7879A4EBD8DE5914CA1814842932C9121F4A5.GeneratedTextTransformation.TransformText()
Thanks in advance
|
|
|
|
|
There is a specific sub-forum on StackOverFlow for PetaPoco questions: [^] ... I think you are more likely to get a response there.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
Thanks 
|
|
|
|
|
It looks like Petapoco for .NET Core hasn't been updated to support version .NET Core 2.0. Based from this [^], the latest release for Petapoco for .NET Core was released last Sept. 2016 and .NET Core 2.0 was released mid of 2017. Perhaps you should try using .NET Core version 1.x instead.
Though, I would still recommend you to ask folks from Petapoco dedicated forums to confirm if it is already integrated to support .NET Core 2.0.
|
|
|
|
|
Thanks for your reply, I will try that
|
|
|
|
|
If you have a Class for example called Character and under character there are other things included like 1.name 2.three descriptive traits 3. personality traits 4.job title And 5. motivation
How is the code going to look like? or
I am required to put them in the main program?
please help! AND Thanks in advance
|
|
|
|
|
You have described at least 2 class requirements. Your character will have single item attributes (name, job title, motivation) and a collection of multiple attributes (descriptive traits and personality traits. So for the single attributes you have a field and for the multiple attributes you need a List<attributes> collection.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I'd like to add to the useful answer Mycroft gave you ...
To me your question suggests you are new to object-oriented programming ... nothing wrong with that ! Everybody here was "new" ... once
It's important you get a clear understanding of what the fundamental elements of .NET OOP are: Classes, Abstract Classes, Structs, Interfaces, Inheritance.
The best way to do this, imho, is to get a good book and study it carefully. Here are recommendations I have made that people have found useful:
[^], [^].
Some disciplined study ... and lots of experimentation ... will have a great value for you in the near future.
«While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)
|
|
|
|
|
Ignore this specific example, and think more generally: how would you do this in the "real world"?
What information is there that is "single use" and associated with one individual? What information is shared by multiple individuals? And what information is multiply associated with a single individual?
Think about cars for a moment.
"Your car" is a specific vehicle: it has a unique registration, VIN number. But it shares it's manufacturer with many other vehicles, it's model with a large number of those, it's colour with a range of vehicles from other manufacturers, and it has a number of optional features associated with that specific vehicle.
So you have "single use" info: registration, VIN, owner.
"shared" info: manufacturer, model, colour.
"multiple" info: reversing camera, GPS system, leather interior.
So a Car class would need to have a way to contain that:
public class Car
{
public string Registration { get; set; }
public string VIN { get; set; }
public Manufacturer Manufacturer { get; set; }
public Model Model { get; set; }
public Color Color { get; set; }
public List<Option> Options { get; set; }
}
Your problem is the same thing: analyze the data you need to handle, and work out how you need to store it. With a bit of thinking, it should be pretty obvious what you need to do - so try it with several examples, and refine your model until it works with everything you can think of.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi,
i need help.
How to when select item from listview from Form1 and click button, to open it Form2 and focus that item to combobox.
Thank you in advance !
|
|
|
|
|
Why do you have a ListView and a ComboBox if they both contain the same items?
What's the point of switching forms if it's the same data? And the same "selected item"?
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|