laslavinco laslavinco - 1 month ago 21
C# Question

How to pass an argument to new RoutedEventHandler menthod in C#?

Hey guys i am new to C# i am learning it. I think code i am trying to make an application launcher and in the end i am trying to pass and extra argument to RoutedEventHandler method call but its giving me an error, i tried looking it up on google but i didn't understand a damn thing. (i am noob) so here is the code please have a look and it.Thanks

namespace Button_Launcher
{

public partial class MainWindow : Window
{
private string line;

public MainWindow()
{
InitializeComponent();

}

private void button_Click(object sender, RoutedEventArgs e)
{

OpenFileDialog fileName = new OpenFileDialog();
fileName.Filter = "executables (.exe)|*.exe";
fileName.ShowDialog();
StreamWriter writer = new StreamWriter("E:/Config.txt",true);
writer.WriteLine(fileName.FileName);
writer.Close();
textBox.Text = fileName.FileName;



}

private void button1_Click(object sender, RoutedEventArgs e)
{
string file = ("E:/Config.txt");

StreamReader Reader = new StreamReader(file, Encoding.ASCII);
List<string> appList = new List<string>();

List<string> Items = new List<string>();
int count = 1;
while ((line = Reader.ReadLine()) != null)
{
makeButton(line,count);
count++;
}
Reader.Close();

}

public void makeButton(string link,int count)
{
string[] mySplit = link.Split(new char[] { '\\' });
string[] name = mySplit.Last().Split(new char[] { '.' });
string fName = name.First();
string buttonName = fName;
Button newBtn = new Button();
newBtn.Content = buttonName;
newBtn.Height = 30;
newBtn.Width = 70;
newBtn.Margin = new Thickness(-60, 90*count/1.5, 180,80);
StackPanel sp = new StackPanel();
sp.Children.Add(newBtn);
mainGrid.Children.Add(sp);
newBtn.Click += new RoutedEventHandler(launchApp(link));
//launchApp(link);


}
private void launchApp(string link,object sender, RoutedEventArgs e)
{

Process.Start(link);
}
}
}

Answer

You cannot change the method signature of the RoutedEventHandler. Instead, try storing the link data in the Tag property of your button. Then in the method you could cast the sender object to a button and access the tag property.

public void makeButton(string link,int count)
{
    string[] mySplit = link.Split(new char[] { '\\' });
    string[] name = mySplit.Last().Split(new char[] { '.' });
    string fName = name.First();
    string buttonName = fName;
    Button newBtn = new Button();
    newBtn.Content = buttonName;
    newBtn.Height = 30;
    newBtn.Width = 70;
    newBtn.Tag = link;
    newBtn.Margin =  new Thickness(-60, 90*count/1.5, 180,80);
    StackPanel sp = new StackPanel();
    sp.Children.Add(newBtn);
    mainGrid.Children.Add(sp);
    newBtn.Click += launchApp;
    //launchApp(link);


}
private void launchApp(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
    if( btn == null )
        return;

    Process.Start(btn.Tag.ToString( ));
}
Comments