Working With ListBox In Windows Phone 7

In this article we discuss how to show images and data in the ListBox in WP7. Here we get the isolated storage data. In this example, we take some information regarding the student and save it and show in the form of a list. Here we use a default image, that will be shown with the student name in the listbox. For this, use the following.

Step 1

For this we first click on "New Project" and the following window will be shown:

WP7.1.jpg

Step 2

After that we change the Background Image of our project so that it will look nice. For this we create a new folder (Image) and add the image to the folder. After that we write the following code in the <Grid> like this:

<Grid x:Name="StudenttNameGrid" Margin="-1,4,1,-4">

                <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="69*" />

                    <ColumnDefinition Width="387*" />

                </Grid.ColumnDefinitions>

                <Grid.Background>

                    <ImageBrush ImageSource="/WorkingWithListBoxInWP7;component/Image/wooden-background.jpg" />

                </Grid.Background>

    </Grid>

</Grid>

Step 3

After that we add a Button control and a Listbox control in our page and we set the visibility property of the TextBox to none so when there is no data in the list, the list will not be visible:

WP7.2.jpg

Code
 

<TextBlock Height="42" HorizontalAlignment="Left" Margin="129,18,0,0" Name="textBlock1" Text="Add Contact" VerticalAlignment="Top" Grid.Column="1" FontWeight="Bold" Width="170" FontSize="28" FontFamily="Calibri" FontStyle="Normal" TextAlignment="Center" />

                <Button Height="67" HorizontalAlignment="Left" Margin="297,4,0,0" Name="btnAddContact" VerticalAlignment="Top" Width="71" FontSize="28" Grid.Column="1" FontWeight="Normal" Click="btnAddContact_Click">

                    <Button.BorderBrush>

                        <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">

                            <GradientStop Color="Black" Offset="0" />

                            <GradientStop Color="#FE897764" Offset="0.707" />

                            <GradientStop Color="BurlyWood" Offset="0" />

                            <GradientStop Color="#FFA37F54" Offset="0" />

                        </LinearGradientBrush>

                    </Button.BorderBrush>

                    <Button.Background>

                        <ImageBrush ImageSource="/WorkingWithListBoxInWP7;component/Image/Add%20Button.png" />

                    </Button.Background>

                </Button>

                <ListBox Height="257" HorizontalAlignment="Left" Margin="42,190,0,0" Name="lstContactname" VerticalAlignment="Top" Width="375" FontSize="22" Foreground="White" FontWeight="Bold" Grid.ColumnSpan="2" Background="{x:Null}" BorderBrush="{x:Null}">

                    <ListBox.ItemTemplate> 

                        <DataTemplate> 

                            <StackPanel Orientation="Horizontal">
                                <Image Source="/WorkingWithListBoxInWP7;component/Image/Untitled.png" Width="55" Height="35" />
                                <TextBlock  Width="20" Height="20"  />
                                <TextBlock Text="{Binding Extra}" Width="200" Height="35" Name="txtBlkExtra" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>

                </ListBox>

Here we use two images, one for the "Add Student" Button and another for showing the data with images in the ListBox.

In this program when we click on the add contact button it will redirect us to a new page where we add the basic information about the student.

Step 4

For this first we create a new page, now we add a new page (AddData.xaml) and on the Click event of the Add Button we write the following code (this will navigate us to the new page):

private void btnAddStudent_Click(object sender, RoutedEventArgs e)

{

    NavigationService.Navigate(new Uri("/StudentDetails.xaml", UriKind.Relative));

}

Step 5

Now we add controls in the new page like this:

WP7.3.jpg

Here we use two buttons, if we want to add the data we will be click on the Add Data Button and if we don't want to add something then we will click on the Finish Button.

Step 6

After that, we will add a Class (StudentInfo.cs) in order to create a table in which we add the Student Information like this:
 

public class StudentInfo

{

    [Column(Storage = "Id", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]

    public string Id

    {

        get;

        set;

    }

      

    [Column(CanBeNull = true)]

    public string FirstName

    {

        get;

        set;

    }

    [Column(CanBeNull = true)]

    public string LastName

    {

        get;

        set;

    }

 

    [Column(CanBeNull = false)]

    public string Mobile

    {

        get;

        set;

    }

 

    [Column(CanBeNull = true)]

    public string Telephone

    {

        get;

        set;

    }

 

    [Column(CanBeNull = true)]

    public string Email

    {

        get;

        set;

    }

}


Here we set the Primary key Id, which is Auto Generated. Now we add an another class (StudentDataContext.cs) in which we write the following code:
 

public class StudentDataContext:DataContext

{

     StudentDataContext(string connectionString)

        : base(connectionString)

     {

     }

     public Table<StudentInfo> Contacts

     {

         get

         {

             return this.GetTable<StudentInfo>();

         }

     }

}

Step 7

Now we will write the following code in the Page (StudentDetails.cs):

private const string strConnectionString = @"isostore:/StudentDB.sdf";

public StudentDetails()

{

    InitializeComponent();

    using (StudentdataContext context = new StudentdataContext(strConnectionString))

    {

        if (!context.DatabaseExists())

        {

            context.CreateDatabase();

        }

    }

}


Now we will write the code for the Add Button:
 

private void btnAdd_Click(object sender, RoutedEventArgs e)

{

    using ( StudentdataContext StudentDB = new StudentdataContext(strConnectionString))

    {

        StudentInfo newStudent = new StudentInfo

        {

            FirstName = txtfname.Text.ToString(),

            LastName = txtlastName.Text.ToString(),

            Mobile = txtMobile.Text.ToString(),

            Telephone = txtTelephone.Text.ToString(),

            Email = txtEmail.Text.ToString()

        };

        StudentDB.Students.InsertOnSubmit(newStudent);

        StudentDB.SubmitChanges();

        MessageBox.Show("Add the Student");

    }

    txtfname.Text = "";

    txtlastName.Text = "";

    txtMobile.Text = "";

    txtTelephone.Text = "";

    txtEmail.Text = "";

}


So when we click on the Add Button the data will be added to the database.

Step 7

Now we will click on the Finish Button; it will be redirect us to the Main Page, after that we will write the following code to show the data in the list box with the default image:
 

public MainPage()

{

    InitializeComponent();

           

    using (StudentdataContext context = new StudentdataContext(strConnectionString))

    {

        if (!context.DatabaseExists())

        {

            context.CreateDatabase();

        }

    }

    using (StudentdataContext StudentDB = new StudentdataContext(strConnectionString))

    {

        var a = from b in StudentDB.GetTable<StudentInfo>() select b.Extra;

        //lstStudentname.ItemsSource = a;

        List<StudentInfo> dataSource = new List<StudentInfo>();

        foreach (var x in a)

        {

            dataSource.Add(new StudentInfo() { Extra = x });

         }     

         this.lstContactname.ItemsSource = dataSource;

         if (lstContactname.Items.Count == 0)

         {

             lstContactname.Visibility = Visibility.Collapsed;

         }

         else

         {

             lstContactname.Visibility = Visibility.Visible;

         }

    }

}


The output will be:

WP7.4.jpg


Similar Articles