locked
How to bind the data to gridview based on if else condition? RRS feed

  • Question

  • User393719 posted

    Hi ,I'm new to mobile development and Xamarin as well, I wanted to bind the data from the database to gridview based on if condition, using Xamarin forms cross platform. For Example, If the time in the databse is "00:00:00.0000000", then while displaying it should nt display anything it should be left blank. Please help me Thanks in advance

    Monday, July 20, 2020 12:55 PM

Answers

  • User382871 posted

    can you share a simple example using the condition for time ,please? @DemoCloud Create a custom converter class to transfer the data from a source property to a target property. ``` public class CustomConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var str = (string)value; // value is the binding data if (str.Length < 3) return "A";

        return "B";
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    

    } ```

    Consume the custom converter in a page. ```

    Page.xaml.cs public partial class Page4 : ContentPage { public ObservableCollection Models { get; set; } public Page4() { InitializeComponent();

        Models = new ObservableCollection<Model_4>();
    
        Models.Add(new Model_4 { content = "content_1" });
        Models.Add(new Model_4 { content = "content_2" });
        Models.Add(new Model_4 { content = "content_3" });
        Models.Add(new Model_4 { content = "co" });
    
        BindingContext = this;
    }
    

    } ```

    Check the tutorial: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters

    !

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Tuesday, July 21, 2020 3:06 AM

All replies

  • User41045 posted

    @DemoCloud You need to make use of Converters. Have a look at this: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters

    Monday, July 20, 2020 3:45 PM
  • User393719 posted

    @AnubhavRanjan ,can you share a simple example using the condition for time ,please? I wanted to bind the gridview item based on if else condition,please help. I've gone through the above example Thanks in advance

    Tuesday, July 21, 2020 2:17 AM
  • User382871 posted

    can you share a simple example using the condition for time ,please? @DemoCloud Create a custom converter class to transfer the data from a source property to a target property. ``` public class CustomConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var str = (string)value; // value is the binding data if (str.Length < 3) return "A";

        return "B";
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    

    } ```

    Consume the custom converter in a page. ```

    Page.xaml.cs public partial class Page4 : ContentPage { public ObservableCollection Models { get; set; } public Page4() { InitializeComponent();

        Models = new ObservableCollection<Model_4>();
    
        Models.Add(new Model_4 { content = "content_1" });
        Models.Add(new Model_4 { content = "content_2" });
        Models.Add(new Model_4 { content = "content_3" });
        Models.Add(new Model_4 { content = "co" });
    
        BindingContext = this;
    }
    

    } ```

    Check the tutorial: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters

    !

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Tuesday, July 21, 2020 3:06 AM
  • User393719 posted

    @AnubhavRanjan , Getting error as "specified cast is not valid" below is the code public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {

            var str = (string)value; // value is the binding data
            if (str == ("2020-06-11").ToString())
                return "A";
    
            return "B";
        }
    

    please help Thanks

    Tuesday, July 21, 2020 3:37 AM
  • User382871 posted

    Getting error as "specified cast is not valid" What type of property did you use to set data binding? The string type? The 'value' is object type, convert it to the type you specified in the model class.

    Tuesday, July 21, 2020 5:21 AM
  • User393719 posted

    @YelinZh I'm still getting the error, please help me,Below is the updated code. public class Class1: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var date = (DateTime)value; DateTime dResult = DateTime.ParseExact("00:00:00.0000000", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); if (date == dResult) return ""; return "B";

        }
        public object Convert1(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var date = (DateTime)value;
            DateTime dResult = DateTime.ParseExact("00:00:00.0000000", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
            if (date == dResult)
                return "";
            return "B";
    
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Page3.xaml

    <ContentPage.Content>
        <ListView x:Name="Models">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding from_time,Converter={StaticResource _converter}}"/>
                            <Label Text="{Binding to_time,Converter={StaticResource _converter1}}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
    

    Page3.xaml.cs public Page3() { InitializeComponent();

            GetDetails();
        }
    
        public async void GetDetails()
        {
            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync("http://******/api/time/Gettimedetails");
            var details = JsonConvert.DeserializeObject<List<Rostercs>>(response);
            Models.ItemsSource = details;
            //ListView1.ItemsSource = details;
    
        }
    

    and also while returning the value instead of "B" i want to return it from the database. In the database if the time is not selected then by default it will be stored as 00:00:00.0000000 Please help

    Tuesday, July 21, 2020 2:19 PM
  • User382871 posted

    @DemoCloud Try to use the following constructor method to create the dateTime for the binding property. Then get the time value from the binding property and compare it with the default value. public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);

    Check the code:

    Page.xaml <Label Text="{Binding date_time, StringFormat='date is: {0}', Converter={StaticResource date_converter}}" /> Page.xaml.cs ``` public partial class Page4 : ContentPage { public ObservableCollection Models { get; set; } public Page4() { InitializeComponent();

        Models = new ObservableCollection<Model_4>();
        Models.Add(new Model_4 { ... date_time = new DateTime(2015, 12, 31, 5, 10, 20, 111) });
        Models.Add(new Model_4 { ... date_time = new DateTime(2015, 12, 31, 5, 10, 20, 000) });
        Models.Add(new Model_4 { ... date_time = new DateTime(2015, 12, 31, 5, 10, 20, 123) });
        Models.Add(new Model_4 { ... date_time = new DateTime(2015, 12, 31, 5, 10, 20, 456) });
    
        BindingContext = this;
    }
    

    } Custom converter class public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var date = (DateTime)value; var time = date.TimeOfDay.ToString();

        if (time == "00:00:00.0000000")
            return "";
        return "B";
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    

    } ```

    Wednesday, July 22, 2020 6:02 AM