locked
Populating ListView with the data got through Web Services

    Question

  • I am developing a Window Store App in which item list is to be populated with grid containing an image and two text blocks. I made a class for assigning values to the items in a grid. The data is to be populated from data base through web service. This is the whole class and its functions for retrieving data and assigning it to the attributes of class.

    public class ITEMS
        {
            private string _Name = string.Empty;
            public string Name
            {
                get
                { return this._Name; }
                set
                { this._Name = value; }
            }
    
    
            private string _UName = string.Empty;
            public string UName
            {
                get
                { return this._UName; }
                set
                { this._UName = value; }
            }
    
    
            private ImageSource _Image = null;
            public ImageSource Image
            {
                get
                { return this._Image; }
                set
                { this._Image = value; }
    
            }
            public void SetImage(Uri baseUri, String path)
            {
                Image = new BitmapImage(new Uri(baseUri, path));
            }
        }
        public class ImageChannel
        {
            public async Task<int> GetCount()
            {
                Service1Client GetItemDetail = new Service1Client();
                GetCountRequest GP = new GetCountRequest();
                GetCountResponse GR = await GetItemDetail.GetCountAsync(GP);
                await GetItemDetail.CloseAsync();
                return GR.GetCountResult;
            }
    
            public async void DisplayInItemList()
            {
                Service1Client GETDETAIL = new Service1Client();
                GetNameAndImageRequest GetDetailRequest = new GetNameAndImageRequest();
                ITEMS item;
                Task<int> COUNT = GetCount();
                int x = COUNT.Result;
                for (int i = 0; i < x; i++)
                {
                    GetDetailRequest.ID = i;
                    GetNameAndImageResponse GetDetailResponse = await GETDETAIL.GetNameAndImageAsync(GetDetailRequest);
                    item = new ITEMS();
                    item.Name = GetDetailResponse.GetNameAndImageResult.NAME;
                    item.UName = GetDetailResponse.GetNameAndImageResult.USERNAME;
    
    
                    byte[] IMG = GetDetailResponse.GetNameAndImageResult.IMAGE;
                    BitmapImage bitMapImage = new BitmapImage();
                    using (InMemoryRandomAccessStream raStream = new InMemoryRandomAccessStream())
                    {
                        using (DataWriter writer = new DataWriter(raStream))
                        {
                            writer.WriteBytes(IMG);
                            await writer.StoreAsync();
                            await writer.FlushAsync();
                            writer.DetachStream();
                        }
                        raStream.Seek(0);
                        bitMapImage.SetSource(raStream);
                    }
                    item.Image = bitMapImage;
                }
            }
    
            public ImageChannel()
            {
                DisplayInItemList();
            }
            List<ITEMS> collection = new List<ITEMS>();
            public List<ITEMS> Collection
            {
                get
                {
                    return this.collection;
                }
            }
        }


    The Web Service method for retrieval is below

            public GetItemDetail GetNameAndImage(int ID)
            {
                StoryMakerConnection.Open();
                string NAMECOMMAND;
                GetItemDetail GID = new GetItemDetail();
                NAMECOMMAND = "SELECT UserFirstName, UserLastName, Picture FROM UserInfo WHERE UserId =" + ID;
                SqlCommand GetPeopleCommand = new SqlCommand(NAMECOMMAND, StoryMakerConnection);
                SqlDataReader PeopleReader = GetPeopleCommand.ExecuteReader();
                while (PeopleReader.Read())
                {
                    GID.FullName = PeopleReader["UserFirstName"].ToString() + " " + PeopleReader["UserLastName"].ToString();
                    GID.img = System.Text.Encoding.UTF8.GetBytes(PeopleReader["Picture"].ToString());
                }
                PeopleReader.Close();
                SqlCommand UserNameCommand = new SqlCommand("SELECT UserName FROM LoginInfo WHERE UserId =" + ID, StoryMakerConnection);
                SqlDataReader UserNameReader = UserNameCommand.ExecuteReader();
                while (UserNameReader.Read())
                    GID.UserName = UserNameReader["UserName"].ToString();
                UserNameReader.Close();
                return GID;
    
            }


    I call it on OnNavigated to event like this

            ImageChannel messageData = new ImageChannel();
            lstPeoples.ItemsSource = messageData.Collection;
     

    This whole effort is not populating the data in the list view. The xaml code for list view is as followed

            <ListView x:Name="lstPeoples" HorizontalAlignment="Left" Height="467" Margin="871,47,0,0" Grid.Row="1" VerticalAlignment="Top" Width="465" SelectionMode="Multiple" Background="{StaticResource AppBarItemDisabledForegroundThemeBrush}" Grid.RowSpan="2">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Height="80">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="120" />
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Image x:Name="imgUser" Height="150" Source="{Binding item.Image}" />
                            <StackPanel Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Bottom">
                                <TextBlock Text="{Binding item.UName}" FontSize="25"  Width="400"/>
                            </StackPanel>
                            <TextBlock Grid.Column="2" VerticalAlignment="Top" FontSize="30" Text="{Binding item.Name}"/>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

    Please help me out.

    Thursday, April 10, 2014 10:17 PM

All replies

  • Hi Waqas,

    Quite a long code snippet, I would like suggest you to set a breakpoint on your OnNavigated method to see if the messageData.Collection is null.

    If it is null, the problem should be on your WCF side, however I cannot test for you, but I think you could debug the code step by step to find out what's wrong.

    If it is a collection, then the problem should be on binding stuff. I looked in your Binding code, seems you do not need "item" in your binding, should be something like:

    <TextBlock Grid.Column="2" VerticalAlignment="Top" FontSize="30" Text="{Binding Name}"/>
    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Friday, April 11, 2014 2:38 AM
    Moderator
  • I think your problem might be that you're using:

    {Binding item.Image} 

    instead of simply:

    {Binding Image}



    Unless I'm misreading your code (I'm new to C#).

    I'm a self-taught noob amateur. Please take this into account when responding to my posts or when taking advice from me.

    Friday, April 11, 2014 5:22 AM
  • Sorry, that is the edited code. First I wrote only "Name" but it was also not working. I debugged it many times by inserting breakpoints on many places, but there was nothing. I checked the WCF side, it is working properly, returning all values efficiently and items is adding these values in its attributes
    for (int i = 1; i <= x; i++)
                {
                    GetNameAndImageRequest GetDetailRequest = new GetNameAndImageRequest();
                    GetDetailRequest.ID = i;
                    GetNameAndImageResponse GetDetailResponse = await GETDETAIL.GetNameAndImageAsync(GetDetailRequest);
                    item = new ITEMS();
                    item.Name = GetDetailResponse.GetNameAndImageResult.NAME;
                    item.UName = GetDetailResponse.GetNameAndImageResult.USERNAME;
                    Collection.Add(item);
                }

    , but still not populating. I am stuck here, neither can go forward not back.
    Friday, April 11, 2014 1:40 PM
  • You've read correctly, but I did that after I failed by using only "Image". Nothing is working for me now :-(
    Friday, April 11, 2014 1:41 PM
  • Hi

    Firstly to address the issues like this

    Please always peep into your output window. The path related errors are shown in the output window, basically shown as binding errors. So check your getting binding error for the image property.

    Another thing to point out here is=> Its always good to use ObeservableCollection to bind your Source.

    You have lot of await calls if your UI needs to get updated at any point of time its always better to use ObservableCollection rather than a List.

        ImageChannel messageData = new ImageChannel();
        lstPeoples.ItemsSource = new ObservableCollection<ITEMS>(messageData.Collection);

    public ImageChannel()
            {
    Initialize();
            }

     private Task<bool> Initialize()
            {
      await DisplayInItemList();

    return true;

    }

    Change the return typeof DisplayInItemList to Task<bool> and return true in the end.

    Since you are not awaiting the call the task may run after the UI has loaded which could be solved by usage of Observable collection and the code changes suggested.

    Lastly,

    Please assign height and width to the image. 

    Regards


    Varun Ravindranath Please 'Mark as Answer' if my post answers your question and 'Vote as Helpful' if it helps you.

    Sunday, April 13, 2014 4:49 AM