ARTICLE

Fetching selected value from List Box in Silverlight

Posted by Dhananjay Kumar Articles | Silverlight with C# September 26, 2011
Here you will see how to Fetch the selected value from a List Box in Silverlight.
Reader Level:

Let us say you have a list box as below. You have a requirement that on click of button fetch value of the same row button belongs to.

For example if you are clickingthe second cross, you should be able to fetch the value Pinal, SqlServer , 500 from the list box.

LstSil1.gif

In the above list box

  1. There is a button (cross image) in each item.
  2. Text blocks bind with data.
  3. List box is bind to the collection.

XAML of list box is as below,

   <ListBox x:Name="lstData" Margin="5,7,6,15">
                <ListBox.ItemTemplate>
                    <DataTemplate >
                        <Grid x:Name="TopGrid">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Button Margin="5,5,5,5" Click="Button_Click">
                                <Button.Template >
                                    <ControlTemplate >
                                        <Image Source="delete.png" VerticalAlignment="Center"   Height="30" Width="30"/>
                                    </ControlTemplate>
                                </Button.Template>
                            </Button>
                            <Grid x:Name="nestedGrid" Grid.Column="1">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto" />
                                <RowDefinition Height="auto" />
                            </Grid.RowDefinitions>                           
                           
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}" />
                                <StackPanel Grid.Row="1" Orientation="Horizontal">
                                    <TextBlock Text="{Binding Interest}"  Style="{StaticResource PhoneTextSubtleStyle}" />
                                <TextBlock Text="{Binding Totalposts}" Style="{StaticResource PhoneTextAccentStyle}"/>
                            </StackPanel>
                        </Grid>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>

Item source of list box is set to List of Bloggers.

LstSil2.gif

Bloggers is a custom class as below,

public class Bloggers : INotifyPropertyChanged
    {
        private string name;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                NotifyPropertyChanged("Name");
                name = value;
            }
        }

        private string interest;
        public string Interest
        {
            get
            {
                return interest;
            }
            set
            {
                NotifyPropertyChanged("Interest");
                interest = value;
            }
        }

        private int  id;
        public int  Id
        {
            get
            {
                return id;
            }
            set
            {
                NotifyPropertyChanged("Id");
                id = value;
            }
        }

         private int  totalposts;
         public int Totalposts
        {
            get
            {
                return totalposts;
            }
            set
            {
                NotifyPropertyChanged("Totalposts");
                totalposts = value;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify the page that a data context property changed
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

    }

Now on the click event of button if you want to fetch a particular list item then first take the data context as blogger

LstSil3.gif

Now you will able to use the data as below

LstSil4.gif

For the on click event of button you need to write code as below to fetch  aparticular item list value.

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            Bloggers data = (sender as Button).DataContext as Bloggers;
            ListBoxItem bloggerToDeleteFromListBox = this.lstData.ItemContainerGenerator.ContainerFromIte
(data)
                                                     as ListBoxItem;          
            var Name = data.Name
}


In this way you can fetch the value of a particular list item. I hope this post was useful. Thanks for reading.

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Login to add your contents and source code to this article
post comment
     

ok

Posted by Dhananjay Kumar Sep 27, 2011

Good god, you are always this much explaining. :) Try this: The Button Binding: Button's Tag={Binding} private void Button_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; Bloggers data = btn.Tag as Bloggers; } Your method is not wrong, but this is another way. :)

Posted by Diptimaya Patra Sep 27, 2011

Hi patra , thanks for your comment. Yes that is very much possible with single line of code Bloggers data = Listboxname.SelectedItem as Bloggers; However if you would have noticed in the strating of the post , I am addressing some differnt problem here. and thats what drove me to write this post. Button is part of data template and residing in different container than textbloks . so when you click on button , Listboxname.SelectedItem as Bloggers will always return you null. Just try copying pasting design[XAMl ] I am using . on click of button you will get NULL for the selcted item so to avoid that I am using code mention in this code. having said that , if my approach and understanding is wrong please feel free to correct me.. :)

Posted by Dhananjay Kumar Sep 27, 2011

Bloggers data = Listboxname.SelectedItem as Bloggers;

Posted by Diptimaya Patra Sep 27, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts