Eventhandler function

0

I am building a page (Xamarin, C #, Android), and I have put a button where the definition of the onclick event, forces me to put it as a private EventHandler. The error that throws me is that "not all the code access paths return a value". On the one hand, I do not understand the error, and on the other, I do not understand the statement as such.

button = new Button
{
Text = "Aceptar",
VerticalOptions = LayoutOptions.CenterAndExpand
};

button.Clicked += Boton_press();

private  EventHandler Boton_press3()
{
// 
// Guardar datos en archivo
String filename = "*******ruta";
String contenido = "blablabla";

try
{
FileOutputStream test = new FileOutputStream(filename);
byte[] data = Encoding.ASCII.GetBytes(contenido);
test.Write(data);
test.Close();
DisplayAlert("Configuracion", "Configuracion guardada", "Ok");
}
catch (Exception)
{
DisplayAlert("Error", "Error al escribir fichero a memoria interna", "Ok");
}
}
    
asked by Jordi Maicas Peña 18.04.2018 в 02:53
source

1 answer

2

The property Button#Clicked expects an object of type EventHandler and that same type is returned by the method Boton_press() but you are not returning in any place a EventHandler . You have to return a EventHandler in the method.

Now, to make things easier, try assigning a lambda function instead of returning the EventHandler from the function.

Replaces:

button.Clicked += Boton_press();

By:

button.Clicked += (sender,e) =>{

    String filename = "*******ruta";
    String contenido = "blablabla";

    try
    {
        FileOutputStream test = new FileOutputStream(filename);
        byte[] data = Encoding.ASCII.GetBytes(contenido);
        test.Write(data);
        test.Close();
        DisplayAlert("Configuracion", "Configuracion guardada", "Ok");
    }
    catch (Exception)
    {
        DisplayAlert("Error", "Error al escribir fichero a memoria interna", "Ok");
    }
};

Or you can create a method with the same subject as the property Clicked of Button and assign it to the property:

public void Buton_pressed(object source, EventArgs e)
{
    String filename = "*******ruta";
        String contenido = "blablabla";

        try
        {
            FileOutputStream test = new FileOutputStream(filename);
            byte[] data = Encoding.ASCII.GetBytes(contenido);
            test.Write(data);
            test.Close();
            DisplayAlert("Configuracion", "Configuracion guardada", "Ok");
        }
        catch (Exception)
        {
            DisplayAlert("Error", "Error al escribir fichero a memoria interna", "Ok");
        }
}

Then to assign it would be like this:

button.Clicked += Buton_press;

This what it does is to subscribe the method Buton_press to the click event. Note how the method is not executed here, but the name or reference of the method Buton_press is assigned to it.

    
answered by 18.04.2018 в 04:33