Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Passing Checkbox value to Button click event

Vasanthakumar06Vasanthakumar06 Member ✭✭✭
edited February 12 in Xamarin.Forms

Hi Techie,

How to Pass the check value ischecked = true|| False to button onclick method.

Here is the code . Kindly check and comment it...

  public class Model : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public Model()
        {
            IsChecked = false;
        }
        public string profile_name { get; set; }

        public string user_id { get; set; }

        private bool isChecked;

        public bool IsChecked
        {
            get
            {
                return isChecked;
            }
            set
            {
                isChecked = value;
                NotifyPropertyChanged();
            }
        }
    }

    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Tagfriends : PopupPage
    {
        public IList<Model> Models { get; private set; }
        List<Model> list = new List<Model>();
        public Tagfriends()
        {
            InitializeComponent();

            this.BackgroundColor = Color.White;

            var accessToken = Settings.AccessToken;
             GetUsername(accessToken);






        }



        async void GetUsername(string accessToken)
        {

            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                string url = "Here is my API URL";

                var result = await client.GetStringAsync(url);


                if (result != null)
                {
                    var EmpList = JsonConvert.DeserializeObject<List<Model>>(result);
                    listView.ItemsSource = null;
                    listView.ItemsSource = new ObservableCollection<Model>(EmpList);

                    foreach(var item in EmpList)
                    {
                        list.Add(new Model() { profile_name = item.profile_name, user_id = item.user_id,IsChecked=item.IsChecked });
                    }

                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Create New Group", ex.Message, "OK");
                return;
            }
        }
        private async void Button_Clicked(object sender, EventArgs e)
        {
            await Navigation.PopPopupAsync();

            var result = list.Where(w => w.IsChecked == true).ToList();

            string s = "";

            int index = 0;
            foreach (var model in result)
            {
                s = s + model.profile_name;
                if (index < result.Count - 1)
                {
                    s = s + ",";
                }
                index++;
            }

            MessagingCenter.Send<object, string>(this, "Hi", s);
        }
    }
}

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    First of all , change the public IList<Model> Models { get; private set; } to public ObservableCollection<Model> Models { get; private set; }

    then change the GetUsername code like following format. And change list to Models in Button_Clicked(). I made a DisplayAlert to show the s value.

     public partial class Tagfriends : PopupPage
        {
            public ObservableCollection<Model> Models { get; private set; }
    
            public Tagfriends()
            {
    
                InitializeComponent();
                this.BackgroundColor = Color.White;
    
                var accessToken = Settings.AccessToken;
                GetUsername(accessToken);
    
                BindingContext = this;
            }
    
            async void GetUsername(string accessToken)
            {
    
                try
                {
                    HttpClient client = new HttpClient();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    string url = "Here is my API URL";
    
                    var result = await client.GetStringAsync(url);
    
    
                    if (result != null)
                    {
                        var EmpList = JsonConvert.DeserializeObject<List<Model>>(result);
    
                        Models = new ObservableCollection<Model>(EmpList);
    
                        foreach (var item in EmpList)
                        {
                            Models.Add(item);
                        }
    
                    }
                    else
                    {
    
                    }
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Create New Group", ex.Message, "OK");
                    return;
                }
            }
    
    
    
    
            private async void Button_Clicked(object sender, EventArgs e)
            {
    
                var result = Models.Where(w => w.IsChecked == true).ToList();
    
                string s = "";
    
                int index = 0;
                foreach (var model in result)
                {
                    s = s + model.profile_name;
                    if (index < result.Count - 1)
                    {
                        s = s + ",";
                    }
                    index++;
                }
    
                await DisplayAlert("info",s,"OK");
    
                await Navigation.PopPopupAsync();
            }
        }
    }
    

    I do not know how is your layout code, So I make a test with following layout.

    <pages:PopupPage  xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="PickerDemo.Tagfriends">
        <ContentPage.Content>
            <Frame>
                <StackLayout>
                    <ListView ItemsSource="{Binding Models}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <StackLayout BackgroundColor="#eee"
                            Orientation="Vertical">
                                        <StackLayout Orientation="Horizontal">
                                            <Label Text="{Binding user_id}" TextColor="Green" />
                                            <Label Text="{Binding profile_name}" TextColor="#f35e20" />
                                            <CheckBox IsChecked="{Binding IsChecked}"  />
                                        </StackLayout>
                                    </StackLayout>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
    
                    </ListView>
                    <Button Text="save" Clicked="Button_Clicked"></Button>
                </StackLayout>
    
            </Frame>
        </ContentPage.Content>
    </pages:PopupPage>
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • Vasanthakumar06Vasanthakumar06 Member ✭✭✭

    @LeonLu Really Awesome !.Passing Profile_name and User_id is my task . As of passing Profile_name done.

    Once i click the Done button (You can see the screenshot i added early ). Profile name will added over the Address Field and i submit the next page . It will submit only profile name only . But i want user_id too .

    How i can achieve this ?

    private async void BtnRegistration_Clicked(object sender, EventArgs e)
    {

            if (string.IsNullOrEmpty(txtName.Text))
            {
                await DisplayAlert("Input Error", "Name is Required", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtAddress.Text))
            {
                await DisplayAlert("Input Error", "Address is Required", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                await DisplayAlert("Input Error", "Email Address is Required", "OK");
                return;
            }
            bool bEmail;
            bEmail = Regex.IsMatch(txtEmail.Text, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (bEmail == false)
            {
                await DisplayAlert("Input Error", "Invalid Email Address.", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtMobile.Text))
            {
                await DisplayAlert("Input Error", "Mobile Number is Required", "OK");
                return;
            }
            bool b;
            b = Regex.IsMatch(txtMobile.Text, @"^[7-9]\d{9}$");
            if (b == false)
            {
                await DisplayAlert("Input Error", "Invalid Mobile Number.", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                await DisplayAlert("Input Error", "Password is Required", "OK");
                return;
            }
    
            try
            {
                BtnRegistration.IsEnabled = false;
                Model userType = new Model();
                userType.Group_Name = txtName.Text;
                userType.Count_of_Member = txtAddress.Text;
                userType.image = txtEmail.Text;
                userType.Mobile = txtMobile.Text;
                userType.Password = txtPassword.Text;
    
  • LeonLuLeonLu Member, Xamarin Team Xamurai

    Just return the select item's list in MessageCenter of Button_Clicked method.

     private async void Button_Clicked(object sender, EventArgs e)
            {
    
                List<Model>  result = Models.Where(w => w.IsChecked == true).ToList();
    
                MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result);
    
                await Navigation.PopPopupAsync();
            }
    

    In the previous page. you can receive it. All of information about SelectedModels in the list.

      List<Model> SelectedModels;
                MessagingCenter.Subscribe<App, List<Model>>(App.Current, "OneMessage", (snd, arg) =>
                {
                    SelectedModels = arg as List<Model>;
                });
    
  • LeonLuLeonLu Member, Xamarin Team Xamurai

    If reply is helpful, please click the Yes tab under the helpful answer. It will help others who have similar issue.

  • Vasanthakumar06Vasanthakumar06 Member ✭✭✭

    @LeonLu said:
    Just return the select item's list in MessageCenter of Button_Clicked method.

     private async void Button_Clicked(object sender, EventArgs e)
            {
    
                List<Model>  result = Models.Where(w => w.IsChecked == true).ToList();
            
                MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result);
    
                await Navigation.PopPopupAsync();
            }
    

    In the previous page. you can receive it. All of information about SelectedModels in the list.

      List<Model> SelectedModels;
                MessagingCenter.Subscribe<App, List<Model>>(App.Current, "OneMessage", (snd, arg) =>
                {
                    SelectedModels = arg as List<Model>;
                });
    

    @LeonLu Where to mention this previous page code .

    But profile name is not reflecting . Returning only null value.

    using this code
    List SelectedModels;

            MessagingCenter.Subscribe<App, List<Model>>(App.Current, "OneMessage", (snd, arg) =>
            {
                SelectedModels = arg as List<Model>;
            });
    
  • LeonLuLeonLu Member, Xamarin Team Xamurai

    After MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result); executed, then MessagingCenter.Subscribe<App, List<Model>>( ) will be executed automatically

  • Vasanthakumar06Vasanthakumar06 Member ✭✭✭

    @LeonLu said:
    After MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result); executed, then MessagingCenter.Subscribe<App, List<Model>>( ) will be executed automatically

    Its not working for me .Here i mentioned Two pages. From Taggingfriends to Newpage i need to transfer the result. And I need to bind only profile name

    inside the result. I'm passing User_id,Profile_name,Ischecked

    So i need to bind profile_name in the Entry field ("txtAddress").

    When i submit the Newpage.

    I need to get the profile_name ,User_id as well as ? How to Achieve this ?

    Did you understand my problem ?

    ****Taggingfriend.xaml.cs****
    private async void Button_Clicked(object sender, EventArgs e)
    {
    List result = Models.Where(w => w.IsChecked == true).ToList();

            string s = "";
    
            int index = 0;
            foreach (var model in result)
            {
                s = s + model.profile_name;
                if (index < result.Count - 1)
                {
                    s = s + ",";
                }
                index++;
            }
    
            // await DisplayAlert("info", s, "OK");
    
            await Navigation.PopPopupAsync();
            MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result);
    
            MessagingCenter.Subscribe<App, List<Model>>();   
    
            //MessagingCenter.Send<object, string>(this, "Hi", s);
        }
    

    Nextpage.xaml

    <ContentPage.Content>


                <Entry Placeholder="Name" TextColor="Black" x:Name="txtName"></Entry>
    
                <Editor Placeholder="Address" TextColor="Black" x:Name="txtAddress" Focused="txtAddress_Focused" HeightRequest="50"></Editor>
    
                <Entry Placeholder="Email-Id"  Keyboard="Email" TextColor="Black" x:Name="txtEmail"></Entry>
    
                <Entry Placeholder="10 Digit Mobile No" Keyboard="Numeric" TextColor="Black" x:Name="txtMobile"></Entry>
    
                <Entry Placeholder="Password" TextColor="Black" x:Name="txtPassword" IsPassword="True"></Entry>
    
    
                <Button Text="Register" HorizontalOptions="FillAndExpand" x:Name="BtnRegistration"     
                 Clicked="BtnRegistration_Clicked"></Button>
    
                <Button Text="Update" HorizontalOptions="FillAndExpand" x:Name="BtnUpdate"     
                 Clicked="BtnUpdate_Clicked" ></Button>
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
    

    Newpage.xaml.cs

    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Newpage : ContentPage
    {

        public Newpage(Groups user)
        {
            InitializeComponent();
            List<Model> SelectedModels;
            MessagingCenter.Subscribe<App, List<Model>>(this, "OneMessage", (obj, result) =>
            {
                SelectedModels = result as List<Model>;
    
            });
            if (user.Group_Name != null && user.Count_of_Member != null && user.image != null && user.Mobile != null && user.Password != null)
            {
    
                txtName.Text = user.Group_Name;
                txtAddress.Text = user.Count_of_Member;
                txtEmail.Text = user.image;
                txtMobile.Text = user.Mobile;
    
                txtMobile.IsEnabled = false;
                txtPassword.Text = user.Password;
                BtnRegistration.IsVisible = false;
                BtnUpdate.IsVisible = true;
            }
            else
            {
                txtMobile.IsEnabled = true;
                BtnRegistration.IsVisible = true;
                BtnUpdate.IsVisible = false;
            }
        }
    
        private async void BtnRegistration_Clicked(object sender, EventArgs e)
        {
    
            List<Model> SelectedModels;
            MessagingCenter.Subscribe<App, List<Model>>(this, "OneMessage", (obj, result) =>
            {
                SelectedModels = result as List<Model>;
            });
    
    
            if (string.IsNullOrEmpty(txtName.Text))
            {
                await DisplayAlert("Input Error", "Name is Required", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtAddress.Text))
            {
                await DisplayAlert("Input Error", "Address is Required", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                await DisplayAlert("Input Error", "Email Address is Required", "OK");
                return;
            }
            bool bEmail;
            bEmail = Regex.IsMatch(txtEmail.Text, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (bEmail == false)
            {
                await DisplayAlert("Input Error", "Invalid Email Address.", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtMobile.Text))
            {
                await DisplayAlert("Input Error", "Mobile Number is Required", "OK");
                return;
            }
            bool b;
            b = Regex.IsMatch(txtMobile.Text, @"^[7-9]\d{9}$");
            if (b == false)
            {
                await DisplayAlert("Input Error", "Invalid Mobile Number.", "OK");
                return;
            }
            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                await DisplayAlert("Input Error", "Password is Required", "OK");
                return;
            }
    
            try
            {
                BtnRegistration.IsEnabled = false;
                Groups userType = new Groups();
                userType.Group_Name = txtName.Text;
                userType.Count_of_Member = txtAddress.Text;
                userType.image = txtEmail.Text;
                userType.Mobile = txtMobile.Text;
                userType.Password = txtPassword.Text;
    
    
                string url = "http://127.0.0.1:8080/api/User/SaveUser";
    
                HttpClient client = new HttpClient();
                string jsonData = JsonConvert.SerializeObject(userType);
                StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(url, content);
                string result = await response.Content.ReadAsStringAsync();
                Response responseData = JsonConvert.DeserializeObject<Response>(result);
                if (responseData.Status == 1)
                {
                    await Navigation.PopAsync();
                    BtnRegistration.IsEnabled = true;
    
                }
                else
                {
                    await DisplayAlert("Message", responseData.Message, "ok");
                    BtnRegistration.IsEnabled = true;
                    return;
                }
    
                BtnRegistration.IsEnabled = true;
            }
            catch (Exception ex)
            {
                await DisplayAlert("Message", ex.Message, "ok");
                BtnRegistration.IsEnabled = true;
                return;
            }
    
    
    
        }
    
  • Vasanthakumar06Vasanthakumar06 Member ✭✭✭

    @LeonLu I got this error Finally

  • Vasanthakumar06Vasanthakumar06 Member ✭✭✭

    @LeonLu said:
    After MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result); executed, then MessagingCenter.Subscribe<App, List<Model>>( ) will be executed automatically

    Its not worked . Kindly check and let me know

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    Why you add Send and Subscribe In the same Button_Clicked event? it is wrong.

    private async void Button_Clicked(object sender, EventArgs e)
    {
    List result = Models.Where(w => w.IsChecked == true).ToList();
    
            string s = "";
    
            int index = 0;
            foreach (var model in result)
            {
                s = s + model.profile_name;
                if (index < result.Count - 1)
                {
                    s = s + ",";
                }
                index++;
            }
    
            // await DisplayAlert("info", s, "OK");
    
            await Navigation.PopPopupAsync();
            MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result);
    
            MessagingCenter.Subscribe<App, List<Model>>();   
    
            //MessagingCenter.Send<object, string>(this, "Hi", s);
        }
    

    And you add two MessagingCenter.Subscribe in Newpage, Could you gave me more details what is your achievement? If you do not know how to use MessagingCenter, please read this article or just post your demo( tell me your needs).

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

    Based on your Nextpage.cs, please make following test. I pop up window in BtnRegistration_Clicked ,

      public partial class Nextpage : ContentPage
        {
            List<Model> SelectedModels=new List<Model>();
            public Nextpage()
            {
                InitializeComponent();
    
    
                MessagingCenter.Subscribe<App, List<Model>>(App.Current, "OneMessage", (snd, arg) =>
                {
                    Model model = arg.FirstOrDefault<Model>();
                    txtName.Text = model.profile_name;
                    txtEmail.Text = model.user_id;
    
    
                });
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
    
            }
    
            private async void BtnRegistration_Clicked(object sender, EventArgs e)
            {
                await Navigation.PushPopupAsync(new Tagfriends());
            }
    
            private void BtnUpdate_Clicked(object sender, EventArgs e)
            {
    
            }
    
            private void txtAddress_Focused(object sender, FocusEventArgs e)
            {
    
            }
        }
    }
    

    then popup the Taggingfriend page, click the button click event, back to the Nextpage, please copy my code completely to make a test.

        private async void Button_Clicked(object sender, EventArgs e)
            {
    
                List<Model>  result = Models.Where(w => w.IsChecked == true).ToList();
    
    
                MessagingCenter.Send<App, List<Model>>((App)App.Current, "OneMessage", result);
    
    
    
                await Navigation.PopPopupAsync();
            }
    
  • LeonLuLeonLu Member, Xamarin Team Xamurai

    Are there any update for this issue, please reply is helpful, please click the Yes tab under the helpful answer.

Sign In or Register to comment.