• [C#] Call a Function on Button Click
    6 replies, posted
I currently have the following code: [CODE] using System; namespace program { class dialog { Form form = new Form(); form.Height = 50; form.Width = 50; form.Text = "Form"; form.StartPosition = FormStartPosition.CenterScreen() Label text = new Label() { Left=50, Top=50, Text="Install?" }; TextBox box new TextBox() { Left=50, Top=50, Width=350 }; Button install = new Button() { Left=350, Width=100, Text="Install" }; install.Click += (sender, e) => { } form.Controls.Add(box); form.Controls.Add(install); form.Controls.Add(text); form.AcceptButton = install; form.ShowDialog(); return textBox.Text; } } [/CODE] How would I call a function in the "install.Click +=..." line? Would I need to create an event handler?
[code]install.Click += (sender, e) => { SomeFunction(); //This is a lambda, check them out if you want to } [/code]
You probably want to use a/the designer to automatically generate Form code for you.
[QUOTE=dije;45290918][code]install.Click += (sender, e) => { SomeFunction(); //This is a lambda, check them out if you want to } [/code][/QUOTE] Or just point it to the method. [code] install.Click += (sender, e) => SomeFunction; //and if you need to pass something. install.Click += (sender, e) => SomeFunction(e); [/code]
[QUOTE=reevezy67;45292005]Or just point it to the method. [code] install.Click += (sender, e) => SomeFunction; //and if you need to pass something. install.Click += (sender, e) => SomeFunction(e); [/code][/QUOTE] The first version probably doesn't compile, [code]install.Click += (sender, e) => SomeFunction();[/code] should work. However, if the signature matches you can just write [code]install.Click += SomeFunction;[/code].
Oh yeah whoops, I make mistakes like that all the time outside of VS. I have the muscle memory for writing these out in VS with intellisense/resharper by just mashing tab.
If you're using Visual Studio and using winforms, just double click on the button in the form designer and it'll generate the code for you. Also for future reference, questions like this should go in the What Do You Need Help With thread probably [url]http://facepunch.com/showthread.php?t=1250528[/url]
Sorry, you need to Log In to post a reply to this thread.