Introduction

We take our learning way again on Sqlite. We see in short the subjects dealt with in the previous article before continuing. Has discussed yourself about the installation of Sqlite engine, the test project creation, the installation of the available Sqlite-net on Nuget, how to create the database on the telephone Storage to the first application start, to end with the insertion, the modification and the cancellation of the data from the database. In this article we will see a search for information in what way execute between several tables. The current Sqlite version is on 8.3.9 you find to this link, we will still base ourselves on the version 3.8.7.4, used in the previous article, we will see in the order:

  • Creation Finddata screen
  • Creation Result screen 
  • Creation Job class
  • Creation RoleUser class 
  • Modification of the class Parametri_ricerca
  • Insertion of the necessary namespace
  • Implementation of the code in the class DatabaseManagement
  • Modification Insert class
  • Modification Update class
  • Modification MainPage class
  • Test application
  • Conclusion
  • Other resources 

Creation Finddata screen

Before continuing, clear advice to read the first part so as to have what was executed. All the code of example together with the project is available to this link. Going back to the project, place the slider on the folder "Screen", feel mouse right and choose the command "add" and after "new element". In the next dialogue window, we search template "basic page", as shown in figure.


Image 1.1
The available template for the development Windows Phone Store.

Rename the screen in Finddata, and confirm with the button add. After the loading of the screen in the Visual Studio Ide, we modify the existing Xaml code with this.

<Page
     x:Class="SqlLite_Sample.Screen.Finddata"
     xmlns:local="using:SqlLite_Sample.Screen"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <Grid x:Name="LayoutRoot">
 
        <Grid.ChildrenTransitions>
             <TransitionCollection>
                 <EntranceThemeTransition/>
             </TransitionCollection>
         </Grid.ChildrenTransitions>
 
        <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
 
        <!-- Pannello del titolo -->
         <StackPanel Grid.Row="0" Margin="19,0,0,0">
             <TextBlock Text="Sqlite sample" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
             <TextBlock Text="Find data page" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
         </StackPanel>
 
        <!--TODO: il contenuto deve essere inserito all'interno della seguente griglia-->
         <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
             </Grid.RowDefinitions>
 
            <StackPanel x:Name="splRadioButton" Grid.Row="0">
                 <RadioButton
                             x:Name="rbnName"
                             IsChecked="True"
                             Content="Name"
                             Tapped="rbnName_Tapped"/>
                  
                 <RadioButton
                             x:Name="rbnRole"
                             IsChecked="False"
                             Content="Role"
                             Tapped="rbnName_Tapped"/>                   
                  
                 <RadioButton
                             x:Name="rbnAge"
                             IsChecked="False"
                             Content="Age"
                             Tapped="rbnName_Tapped"/>                   
             </StackPanel>
              
             <StackPanel Grid.Row="1">
                 <TextBlock
                             x:Name="tbkName"
                             FontSize="20"               
                             Text="Find data"
                             HorizontalAlignment="Center"
                             VerticalAlignment="Center"/>
                 <TextBox
                             x:Name="tbxFindForName"/>
             </StackPanel>
 
            <Button
                            Grid.Row="2"
                            x:Name="btnFind"
                            Content="Find"
                            HorizontalAlignment="Center"
                            Tapped="btnFind_Tapped"/>
         </Grid>
     </Grid>
< /Page>

How the screen will have to be after the xaml code insertion.


Image 1.2 The screen Find data page.

We have three Radio Button controls what according to what select, can execute a research typology, in our case for name, role and age. We will go to type in a term inside the TextBox control, placed under the given TextBlock Find data, and at the end of the mediating Button Find insertion will start the research procedure according to what we have chosen. With the F7 key, we come in inside the code editor and modify the builder of the class Finddata as follows:

public Finddata()
     {
         this.InitializeComponent();
 
        this.navigationHelper = new NavigationHelper(this);
         this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
         this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
 
        foreach (var control in splRadioButton.Children.OfType<RadioButton>().Where(w => w.Content.Equals("Name")))
         {
             Parametri_ricerca.TypeSearch = control.Content.ToString();
         }
     }

What is executed? We set up default searches for name that is that to give at once the user the possibility of inserting a name, everything going to increase the value of the TypeSearch property of the class Parametri_ricerca with the property value Content of Radio Button which corresponds to term "Name". We must still manage the Tapped Find button event and the Tapped event of the Radio Button controls. To do that we insert inside the class the following C# code.

private async void btnFind_Tapped(object sender, TappedRoutedEventArgs e)
{
     if (Validations.CheckTextBox(tbxFindForName).Equals(true))
     {
         var dialog = new MessageDialog("Inserisci un termine di ricerca!");
         await dialog.ShowAsync();
 
        if(Parametri_ricerca.TypeSearch.Equals(""))
         {
             var dialog1 = new MessageDialog("Inserisci un termine di ricerca!");
             await dialog1.ShowAsync();
         }
     }
 
    else
     {
         Parametri_ricerca.FindData = tbxFindForName.Text;
         Frame.Navigate(typeof(Result));
     }
}
 
private void rbnName_Tapped(object sender, TappedRoutedEventArgs e)
{
     var radiobuttonTapped = sender as RadioButton;
     Parametri_ricerca.TypeSearch = radiobuttonTapped.Content.ToString();
}
We analyze the previous code, we have the Tapped event of the Find button, with which we will execute two validations, and the first if inside the TextBox control there is a value, while the second on the variable value TypeSearch. If one of the validations have unsuccessful result, we will inform the mediating user a MessageDialog, if both validations have positive result, in else code, we go to increase the value of the FindData property of the class Parametri_ricerca with the control value TextBox tbxFindForName and will be then led in the Result screen which we have mentioned before, while for the event Tapped controls RadioButton recover by parameter sender which of the three has selected the user, then exploiting the variable TypeSearch who will take one of the values ​​Content of each RadioButton . 

 

Creation Result screen

Finished this activity in the class Finddata can be responsible for creating the Result screen. In explores solutions, create the Result screen as we have done for Finddata, and in the xaml file we replace the existing code with the following:

<Page
     x:Class="SqlLite_Sample.Screen.Result"
     xmlns:local="using:SqlLite_Sample.Screen"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <Grid x:Name="LayoutRoot">
 
        <Grid.ChildrenTransitions>
             <TransitionCollection>
                 <EntranceThemeTransition/>
             </TransitionCollection>
         </Grid.ChildrenTransitions>
 
        <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
 
        <!-- Pannello del titolo -->
         <StackPanel Grid.Row="0" Margin="19,0,0,0">
             <TextBlock Text="Sqlite sample" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
             <TextBlock Text="Result" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
         </StackPanel>
 
        <!--TODO: il contenuto deve essere inserito all'interno della seguente griglia-->
         <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
             </Grid.RowDefinitions>
             <ListBox Grid.Row="0" x:Name="lstFindPerson">
                 <ListBox.ItemTemplate>
                     <DataTemplate>
                         <StackPanel>
                             <StackPanel Orientation="Horizontal">
                                 <TextBlock x:Name="tbkName"
                                            FontWeight="Bold"
                                            Text="Name"/>
 
                                <TextBlock Width="30"/>
 
                                <TextBlock x:Name="tbkRole"
                                            FontWeight="Bold"                                          
                                            Text="Role"/>
 
                                <TextBlock Width="30"/>
 
                                <TextBlock x:Name="tbkAge"
                                            FontWeight="Bold"                                          
                                            Text="Age"/>
 
                                <TextBlock Height="50"/>
                             </StackPanel>
 
                            <StackPanel Orientation="Horizontal">
                                 <TextBlock
                                     x:Name="tbkFindForName"
                                     Text="{Binding Name}"/>
 
                                <TextBlock Width="20"/>
 
                                <TextBlock
                                     x:Name="tbkFindForRole"
                                     Text="{Binding Role}"/>
 
                                <TextBlock Width="20"/>
 
                                <TextBlock
                                     x:Name="tbkFindForAge"
                                     Text="{Binding Age}"/>
                             </StackPanel>
                         </StackPanel>
                     </DataTemplate>
                 </ListBox.ItemTemplate>
             </ListBox>
         </Grid>
     </Grid>
< /Page>

How the screen will have to be here after the xaml code insertion.


Image 1.3 The screen Result page.

What we have created is simply a ListBox control with inside two StackPanel. In the first will have three TextBlock controls with of the static text, that is name, Role and age, in the second StackPanel, there are three TextBox controls with the Text property in binding to the Name properties, Role and Age of one RoleUser collection, that is the class which will be responsible for showing us the research result, also this class will create it during the article. Ended the graphic part, with the F7 key we go in the code editor, we modify the builder of the class Result as follows.

public Result()
{
     this.InitializeComponent();
 
    this.navigationHelper = new NavigationHelper(this);
     this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
     this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
 
    DatabaseManagement.FindForName(Parametri_ricerca.FindData, Parametri_ricerca.TypeSearch, lstFindPerson);
}

The part which interests in us is the last code line, in other words:

DatabaseManagement.FindForName(Parametri_ricerca.FindData, Parametri_ricerca.TypeSearch, lstFindPerson); 

This method requires three parameters, the term of research that is what we will have to be to insert inside the TextBox control in the Finddata screen, the second parameter is the type of research, which can be in our case for name, role or age. The last parameter is the reference to the control ListBox belonging to the Result screen. We will see the code because header when we must modifying in the class DatabaseManegement.

 

Creation class Job

After defining also the Result screen, he arrived the moment to create the classes necessary for the research function. We go back to the test project, we position the slider over the Classes folder, feel mouse right and we choose the commands "add" and immediately later "class" and call her with the name Job. This class does not do anything else but add a role for every user who we will have to be to insert in the created database to the first application start, by a new table which will have I sharpen the name of the class which we will create in this passage. To created class, we go to replace the current C# code with this following.

using SQLite;
 
namespace SqlLite_Sample.Classes
{
     class Job
     {
         [SQLite.PrimaryKey,AutoIncrement]
         public int Id { get; set; }
 
        [MaxLength(30)]
         public string Name { get; set; }
 
        [MaxLength(30)]
         public string Role { get; set; }
 
        [MaxLength(3)]
         public int Age { get; set; }
     }
}

With this code we have simply defined four properties. The first, int, which will be the primary key. This by the PrimaryKey.Autoincrement attribute, which will think about automatically increasing the property value Id. The second property will be used to define the name, the third the role, and the age finishes it. We notice that for the Name and Role properties, an attribute MaxLength (30) has been defined, that means that both properties will be not able to have a lace value of beyond 30 characters, finishes it int, serves to memorize the user's age, with a maximum of three characters by the attribute MaxLength (3).

 

Creation class RoleUser

Create the last one of the two necessary classes with the same procedure which we have previously used always in the Classes folder, the difference that this time we will name her RoleUser. We go to replace the current C# code with the following.

using SQLite;
 
namespace SqlLite_Sample.Classes
{
     class RoleUser
     {
         [MaxLength(30)]
         public string Name { get; set; }
 
        [MaxLength(30)]
         public string Role { get; set; }
 
        [MaxLength(3)]
         public int Age { get; set; }
     }
}

Also in this case, we have defined three properties, two strings and one int with the attributes used for the properties of the class job on the limit of the 3 and 30 characters. This is the class we will use in binding if you remember on the definite TextBox controls in the class Result.

 

Modification of the class Parametri_ricerca

We must now modify and insert a few properties in this class, since they will serve us during the article to manage update of the information about the user. With the slider positioned on the Classes folder we open the Parametri_ricerca.cs file and modify the existing C# code with the following.

namespace SqlLite_Sample.Classes
{
     public static class Parametri_ricerca
     {
         public static string FindData { get; set; }
         public static string TypeSearch { get; set; }
         public static string NewName { get; set; }
         public static string NewSurName { get; set; }
         public static int NewAge {get;set;}      
     }
} 

Insertion of the necessary namespace

Before modifying the C# code of the class DataBaseManagement, we must insert in the classes' job and RoleUser the following Namespace.

using SqlLite_Sample.Classes;

This is necessary for being able to do use of the class Parametri_ricerca, positioned inside the Classes folder.

 

Implementation of the code in the class DatabaseManagement

We now go to modify the C# code of the class DatabaseManagement. We will go to modify the Insert, Delete and UpdateData methods so as to manage also the new table which will be created to the first start, in other words the table job. In explores solutions double click with the mouse on the DatabaseManagement file and modify the CreateDatabase method as follows.

public static async void CreateDatabase()
{
     await ConnectionDb().CreateTableAsync<Employee>();
     await ConnectionDb().CreateTableAsync<Job>();
}

And been a new line of code, which will not do anything else but create as advance a table called job inside the database people.db join together. We now modify the InsertData method how he follows.

public async static void InsertData(string _name, string _surname, int _age, string _role)
{
     var newemployee = new Employee
     {
         Name = _name,
         SurName = _surname,
         Age = _age,
     };
 
    var newjob = new Job
     {
         Name = newemployee.Name,
         Role = _role,
         Age = newemployee.Age,
     };
 
 
     await ConnectionDb().InsertAsync(newemployee);
     await ConnectionDb().InsertAsync(newjob);
}

We analyze the code in detail. A difference with the previous article, we have added a quarter parameter to the method, where the role of the user, has to be inserted and a new request of the class job, increasing the value of the Name, Role and Age properties respectively with the newemployee.Name values, the _role parameter of the InsertData and newemployee.Age method, and at last we go to memorize and make the information so permanent in the database by the InserAsync method, passing as parameters the instance of the classes Employee and Job. We must modify also the DeleteData method code so as to remove the user at issue from both database tables, the DeleteData method has to be modified as follows:

public async static void DeleteData(string _name)
{
     var deleteemployee = await ConnectionDb().Table<Employee>().Where(w => w.Name.Equals(_name)).FirstOrDefaultAsync();
     deleteemployee.Name = _name;
     await ConnectionDb().DeleteAsync(deleteemployee);
 
    var deleterole = await ConnectionDb().Table<Job>().Where(w => w.Id.Equals(deleteemployee.Id)).FirstOrDefaultAsync();
     await ConnectionDb().DeleteAsync(deleterole);
}

And been this code part join together

var deleterole = await ConnectionDb().Table<Job>().Where(w => w.Id.Equals(deleteemployee.Id)).FirstOrDefaultAsync();
   await ConnectionDb().DeleteAsync(deleterole); 

where we go to verify by the property Equals method Id of the tables Employee and Job, if it is found a correspondence, the user's data will be removed from the table Job, everything with the DeleteAsync method, deleterole of job type coming as I argue the variable. We now modify the UpdateData method code, replacing the current one with the following.

public async static void UpdateData(string _name, string _newname, string _surname, string _newsurname, int _age, int _newage, string _newrole)
{
     var updateemployee = await ConnectionDb().Table<Employee>().Where(w => w.Name.Equals(_name) && w.SurName.Equals(_surname) && w.Age.Equals(_age)).FirstOrDefaultAsync();
     updateemployee.Name = _newname;
     updateemployee.SurName = _newsurname;
     updateemployee.Age = _newage;
     await ConnectionDb().UpdateAsync(updateemployee);
 
    var updaterole = await ConnectionDb().Table<Job>().Where(w=> w.Id.Equals(updateemployee.Id)).FirstOrDefaultAsync();
     updaterole.Name = updateemployee.Name;
     updaterole.Age = updateemployee.Age;
     updaterole.Role = _newrole;
     await ConnectionDb().UpdateAsync(updaterole);
}  

And been the management join together for update of the table job exactly as for the DeleteData method. In other words going to verify the Id property with the Equals method, and if the comparison between the two properties has positive result, Name, Age and Role properties of the table job will assume the new values of updateemployee, Name, updateemployee.Age and parameter_newrole. We now insert the FindForName method; this method there was not in the previous article, as maids to execute the true and real research.

public async static void FindForName(string _name, string _typesearch, ListBox _box)
{
     var employee = new List<Employee>();
     var job = new List<Job>();
     var roleuser = new List<RoleUser>();
 
    var queryName = ConnectionDb().Table<Employee>();
     var resultName = await queryName.ToListAsync();
 
    var queryJob = ConnectionDb().Table<Job>();
     var resultjob = await queryJob.ToListAsync();
 
 
     foreach (var findperson in resultName)
     {
         employee.Add(new Employee { Name = findperson.Name, SurName = findperson.SurName, Age = findperson.Age });
     }
 
    foreach (var findjob in resultjob)
     {
         job.Add(new Job { Name = findjob.Name, Role = findjob.Role, Age = findjob.Age });
     }
 
 
     switch (_typesearch)
     {
         case "Name":
 
            var resultForName = employee
                         .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                             new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Name.Equals(_name))
                             .Distinct();
 
 
             foreach (var newjob in resultForName)
             {
                 roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
             }
 
            break;
 
        case "Role":
             var resultForRole = employee
                         .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                             new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Role.Equals(_name))
                             .Distinct();
 
            foreach (var newjob in resultForRole)
             {
                 roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
             }
 
            break;
 
        case "Age":
             var resultAge = employee
                         .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                             new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Age.Equals(int.Parse(_name)))
                             .Distinct();
 
            foreach (var newjob in resultAge)
             {
                 roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
             }
 
            break;
     }
 
    _box.ItemsSource = roleuser;
}    

We analyze the previous code. Three collections have been defined: one Employee, one of Job type and finishes it RoleUser.

var employee = new List<Employee>();
var job = new List<Job>();
var roleuser = new List<RoleUser>();

This collection except for the RoleUser one will be then increased the value with all the data coming from the tables Employee and Job present in the database people.db. We go to recover the tables Employee and Job later by this code.

var queryName = ConnectionDb().Table<Employee>();
var queryJob = ConnectionDb().Table<Job>();

Exactly with the Table<T>() method, we go to recover the true and real information present in the tables. For finish convert all the content into a list with the following code lines.

var resultName = await queryName.ToListAsync();    
var resultjob = await queryJob.ToListAsync();    

Doing so, we convert the information inside the table into a collection which we can then manipulate to liking according to our demands. Since as I previously see, SqliteNet does not fully support Linq and all Extension Method we must bypass the problem in another way, make it this way, with two foreach cycles increase the value of collection employee and job initially create.

foreach (var findperson in resultName)
{
     employee.Add(new Employee { Name = findperson.Name, SurName = findperson.SurName, Age = findperson.Age });
}
 
foreach (var findjob in resultjob)
{
     job.Add(new Job { Name = findjob.Name, Role = findjob.Role, Age = findjob.Age });
}

Observing the previous code, will understand because we have had converting the information into a list of tables with the ToListAsync () method exposed by the bookshop SqliteNet. We now have all the data in memory to be able to execute the wished research. We now analyze the most important part than the FindForName method, the switch meaning.

switch (_typesearch)
{
     case "Name":
 
        var resultForName = employee
                     .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                         new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Name.Equals(_name))
                         .Distinct();
 
 
         foreach (var newjob in resultForName)
         {
             roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
         }
 
        break;
 
    case "Role":
         var resultForRole = employee
                     .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                         new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Role.Equals(_name))
                         .Distinct();
 
        foreach (var newjob in resultForRole)
         {
             roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
         }
 
        break;
 
    case "Age":
         var resultAge = employee
                     .Join(job, newname => newname.Id, newjob => newjob.Id, (newname, newjob) =>
                         new { newjob.Name, newjob.Role, newjob.Age }).Where(w => w.Age.Equals(int.Parse(_name)))
                         .Distinct();
 
        foreach (var newjob in resultAge)
         {
             roleuser.Add(new RoleUser { Name = newjob.Name, Role = newjob.Role, Age = newjob.Age });
         }
 
        break;
}

We go to verify the variable value _typesearch, which can assume three values, Name, Role or Age. In each of the cases he goes to execute a query Linq on collection employee and job, we will not fully explain Linq why lies outside the article at issue. Query do not do anything else but join collection join by extension method by the Id property of both, and at last with extension method where go to verify a determinate condition, that is the parameter value _name, if it is found one or more correspondences the information which correspond to the specified condition will be selected and extrapolated. At last we increase the value of collection roleuser with the final result of query with the Name, Role and Age values and end with increasing the value of the ListBox _box parameter with the value of collection roleuser, and explained here because we pass on to the FindForName method the control reference ListBox present in the Result screen.

_box.ItemsSource = roleuser;

 

Modification Insert class

Have finished the modifications in the class DatabaseManagement, must still execute some precautions in screens of Insert, Update and MainPage will see thing in detail. Leave from the class Insert, will add a TextBox control where we have the possibility of inserting a role for every new user whom we insert in the table Job in the Database people.db. We go back to our project, position the slider on the Screen folder, and do click double with the mouse on the Insert.xaml file. Opened the file replace the existing Xaml code with this.

<Page
     x:Class="SqlLite_Sample.Screen.Insert"
     xmlns:local="using:SqlLite_Sample.Screen"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <Grid x:Name="LayoutRoot">
 
        <Grid.ChildrenTransitions>
             <TransitionCollection>
                 <EntranceThemeTransition/>
             </TransitionCollection>
         </Grid.ChildrenTransitions>
 
        <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
 
        <!-- Pannello del titolo -->
         <StackPanel Grid.Row="0" Margin="19,0,0,0">
             <TextBlock
                 Text="Sqlite sample"
                 Style="{ThemeResource TitleTextBlockStyle}"
                 Margin="0,12,0,0"/>
              
             <TextBlock
                 Text="Insert page"
                 Margin="0,-6.5,0,26.5"
                 Style="{ThemeResource HeaderTextBlockStyle}"
                 CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
         </StackPanel>
 
        <!--TODO: il contenuto deve essere inserito all'interno della seguente griglia-->
         <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>               
             </Grid.RowDefinitions>
                          
             <Grid Grid.Row="0">
                 <Grid.RowDefinitions>
                     <RowDefinition Height="Auto"/>
                     <RowDefinition Height="Auto"/>
                     <RowDefinition Height="Auto"/>
                     <RowDefinition Height="Auto"/>
                     <RowDefinition Height="Auto"/>
                 </Grid.RowDefinitions>
 
                <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="Auto"/>
                     <ColumnDefinition Width="*"/>
                 </Grid.ColumnDefinitions>
 
                <TextBlock
                             Grid.Column="0"
                             Grid.Row="0"
                             x:Name="tbkName"
                             FontSize="25"               
                             Text="Name"
                             VerticalAlignment="Center"
                 />
 
                <TextBlock
                             Grid.Column="0"
                             Grid.Row="1"               
                             x:Name="tbkSurname"
                             FontSize="25"
                             Text="Surname"
                             VerticalAlignment="Center"
                 />
 
                <TextBlock
                             Grid.Column="0"
                             Grid.Row="2"               
                             x:Name="tbkAge"
                             FontSize="25"
                             Text="Age"
                             VerticalAlignment="Center"
                 />
 
                <TextBlock
                             Grid.Column="0"
                             Grid.Row="3"               
                             x:Name="tbkRole"
                             FontSize="25"
                             Text="Role"
                             VerticalAlignment="Center"
                 />
 
                <TextBox
                             Grid.Column="1"
                             Grid.Row="0"
                             x:Name="tbxName"
                 />
 
                <TextBox
                             Grid.Column="1"
                             Grid.Row="1"               
                             x:Name="tbxSurname"
                 />
 
                <TextBox
                             Grid.Column="1"
                             Grid.Row="2"               
                             x:Name="tbxAge"
                             InputScope="Number"
                 />
 
                <TextBox
                             Grid.Column="1"
                             Grid.Row="3"               
                             x:Name="tbxRole"
                 />
             </Grid>
 
            <Grid Grid.Row="1">
                 <Grid.RowDefinitions>
                     <RowDefinition Height="20"/>
                     <RowDefinition Height="Auto"/>                   
                 </Grid.RowDefinitions>
                  
                 <Button
                            Grid.Row="1"
                            x:Name="btnInsert"
                            Content="Insert"
                            HorizontalAlignment="Center"
                            Tapped="btnInsert_Tapped"
                 />
                  
             </Grid>
         </Grid>
     </Grid>
< /Page> 

This will have to be the new graphic interface after the Xaml code modification.


Image  1.4 The screen Insert page.

Ended the graphic part, I feel F7 to access the code editor and we modify the Tapped event of Button Insert as follows.

private async void btnInsert_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            if(Validations.CheckTextBox(tbxName,tbxSurname,tbxAge).Equals(true))
            {
                var dialog = new MessageDialog("Valorizzare tutti i campi");
                await dialog.ShowAsync();
            }
 
           else
            {
                DatabaseManagement.InsertData(tbxName.Text, tbxSurname.Text, int.Parse(tbxAge.Text),tbxRole.Text);
            }
        }

The difference is in this line of code

DatabaseManagement.InsertData(tbxName.Text, tbxSurname.Text, int.Parse(tbxAge.Text),tbxRole.Text);

If you remember in the InsertData method have added a quarter parameter necessary for inserting the user's role, and here they because of this also modifies in the event Tapped Of Button.

 

Modification class Update

Like the class Insert, also the class Update needs a few modifications, and I date from the fact that in the previous article it was possible to modify only the name of the user, we will give the possibility of modifying the surname, the age and inserting also a new role. Always with the slider positioned on the Screen folder, open the Update.xaml file, and we go to modify the existing xaml code with this.

<Page
     x:Class="SqlLite_Sample.Screen.Update"
     xmlns:local="using:SqlLite_Sample.Screen"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <Grid x:Name="LayoutRoot">
 
        <Grid.ChildrenTransitions>
             <TransitionCollection>
                 <EntranceThemeTransition/>
             </TransitionCollection>
         </Grid.ChildrenTransitions>
 
        <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
 
        <!-- Pannello del titolo -->
         <StackPanel Grid.Row="0" Margin="19,0,0,0">
             <TextBlock Text="Sqlite sample" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
             <TextBlock Text="Update page" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
         </StackPanel>
 
        <!--TODO: il contenuto deve essere inserito all'interno della seguente griglia-->
         <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
             <Grid.RowDefinitions>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>
                 <RowDefinition Height="Auto"/>               
             </Grid.RowDefinitions>
 
 
             <ListBox Grid.Row="0" x:Name="lstUpdatePerson" SelectionChanged="lstUpdatePerson_SelectionChanged">
                 <ListBox.ItemTemplate>
                     <DataTemplate>
                         <StackPanel>
                             <StackPanel Orientation="Horizontal">
                                 <TextBlock x:Name="tbkName"
                                            FontWeight="Bold"
                                            Text="Name"/>
 
                                <TextBlock Width="30"/>
 
                                <TextBlock x:Name="tbkSurname"
                                            FontWeight="Bold"                                          
                                            Text="Surname"/>
 
                                <TextBlock Width="30"/>
 
                                <TextBlock x:Name="tbkAge"
                                            FontWeight="Bold"                                          
                                            Text="Age"/>
 
                                <TextBlock Height="50"/>
                             </StackPanel>
 
                            <StackPanel Orientation="Horizontal">
                                 <TextBlock
                                     x:Name="tbkFindForName"
                                     Text="{Binding Name}"/>
 
                                <TextBlock Width="20"/>
 
                                <TextBlock
                                     x:Name="tbkFindForSurName"
                                     Text="{Binding SurName}"/>
 
                                <TextBlock Width="20"/>
 
                                <TextBlock
                                     x:Name="tbkFindForAge"                                   
                                     Text="{Binding Age}"/>
                             </StackPanel>
                         </StackPanel>
                     </DataTemplate>
                 </ListBox.ItemTemplate>
             </ListBox>
              
             <TextBlock Grid.Row="3" x:Name="tbkNewData" Text="New data" HorizontalAlignment="Center"/>
              
             <StackPanel Grid.Row="4" x:Name="splNewData">
                 <StackPanel x:Name="splNewName" Orientation="Horizontal">
                     <TextBlock Text="Name" VerticalAlignment="Center"/>
                     <TextBlock Width="30"/>
                     <TextBox x:Name="tbxNewName" Width="Auto"/>
                 </StackPanel>
 
                <StackPanel x:Name="splNewSurName" Orientation="Horizontal">
                     <TextBlock Text="SurName" VerticalAlignment="Center"/>
                     <TextBlock Width="15"/>
                     <TextBox x:Name="tbxNewSurName" Width="Auto"/>
                 </StackPanel>
 
                <StackPanel x:Name="splNewAge" Orientation="Horizontal">
                     <TextBlock Text="Age" VerticalAlignment="Center"/>
                     <TextBlock Width="40"/>
                     <TextBox x:Name="tbxNewAge" Width="Auto" InputScope="Number"/>
                 </StackPanel>
 
                <StackPanel x:Name="splNewRole" Orientation="Horizontal">
                     <TextBlock Text="Role" VerticalAlignment="Center"/>
                     <TextBlock Width="40"/>
                     <TextBox x:Name="tbxNewRole" Width="Auto"/>
                 </StackPanel>
             </StackPanel>           
              
             <Button Grid.Row="6" x:Name="btnUpdatePerson" Content="Update" Tapped="btnUpdatePerson_Tapped"/>
         </Grid>
     </Grid>
< /Page> 

Here the new Update screen after the modifications.


Image  1.5 The new screen Update page.

We now modify also the C# code part, feel F7 to access the editor, and go to replace all the content of the Tapped events of button btnUpdatePerson e and SelectionChanged of the ListBox lstUpdatePerson control.

private async void btnUpdatePerson_Tapped(object sender, TappedRoutedEventArgs e)
{
     await Validations.MessageConfirmDeleteoUpdatePerson("Vuoi aggiornare i dati?");
 
    if (Validations.result.Equals(true))
     {
         if (Validations.CheckTextBox(tbxNewName, tbxNewSurName, tbxNewAge).Equals(true))
         {
             var dialog = new MessageDialog("Valorizzare tutti i campi");
             await dialog.ShowAsync();
         }
 
        else
         {
             DatabaseManagement.UpdateData(Parametri_ricerca.NewName,tbxNewName.Text,
                 Parametri_ricerca.NewSurName,tbxNewSurName.Text,Parametri_ricerca.NewAge, int.Parse(tbxNewAge.Text),tbxNewRole.Text);
         }
     
}

He remains all unchanged except this code line

DatabaseManagement.UpdateData(Parametri_ricerca.NewName,tbxNewName.Text,
       Parametri_ricerca.NewSurName,tbxNewSurName.Text,Parametri_ricerca.NewAge, int.Parse(tbxNewAge.Text),tbxNewRole.Text);  

Also in this case, if you remember the UpdateData method has been modified inserting the support to the surname modification, age and the possibility of inserting or modifying the user's role. We still modify the code for the ListBox control.

private void lstUpdatePerson_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Parametri_ricerca.NewName = ((Employee)(lstUpdatePerson.SelectedValue)).Name;
            Parametri_ricerca.NewSurName = ((Employee)(lstUpdatePerson.SelectedValue)).SurName;
            Parametri_ricerca.NewAge = ((Employee)(lstUpdatePerson.SelectedValue)).Age;          
 
           tbxNewName.Text = ((Employee)(lstUpdatePerson.SelectedValue)).Name;
            tbxNewSurName.Text = ((Employee)(lstUpdatePerson.SelectedValue)).SurName;
            tbxNewAge.Text = ((Employee)(lstUpdatePerson.SelectedValue)).Age.ToString();
        }

Also in this case have added the support for the surname modification and age adding these code lines which do not do anything else but increase the value of the UpdateData method parameters.          

Parametri_ricerca.NewSurName = ((Employee)(lstUpdatePerson.SelectedValue)).SurName;
 Parametri_ricerca.NewAge = ((Employee)(lstUpdatePerson.SelectedValue)).Age;         
 
tbxNewSurName.Text = ((Employee)(lstUpdatePerson.SelectedValue)).SurName;
 tbxNewAge.Text = ((Employee)(lstUpdatePerson.SelectedValue)).Age.ToString();

 

Modification class MainPage

Finishes modification to be executed, the initial application screen, add such a button to be able to access the Finddata screen created previously. We modify the xaml code how he follows.

<Page
     x:Class="SqlLite_Sample.MainPage"
     xmlns:local="using:SqlLite_Sample"
     mc:Ignorable="d"
     Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <Grid x:Name="LayoutRoot">
 
        <Grid.ChildrenTransitions>
             <TransitionCollection>
                 <EntranceThemeTransition/>
             </TransitionCollection>
         </Grid.ChildrenTransitions>
 
        <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
 
        <!-- Pannello del titolo -->
         <StackPanel Grid.Row="0" Margin="19,0,0,0">
            <TextBlock Text="Sqlite sample" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
            <TextBlock Text="Main page" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
         </StackPanel>
 
        <!--TODO: il contenuto deve essere inserito all'interno della seguente griglia-->
         <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,9.5,19,0">
             <StackPanel>
                <Button
                     x:Name="btnInsertSample"
                     Content="Insert sample page"
                     Tapped="btnInsertSample_Tapped"
                     Width="300"/>
                  
                 <Button
                     x:Name="btnUpdateSample"
                     Content="Update sample page"
                     Tapped="btnUpdateSample_Tapped"
                     Width="300"/>
                  
                <Button
                     x:Name="btnDeleteSample"
                     Content="Delete sample page"
                     Tapped="btnDeleteSample_Tapped"
                     Width="300"/>
 
                <Button
                     x:Name="btnFindSample"
                     Content="Find sample page"
                     Tapped="btnFindSample_Tapped"
                     Width="300"/>
             </StackPanel>
         </Grid>
     </Grid>
< /Page> 

Here the new Main Page screen after the modifications.


Image  1.6 The modified Main page screen.

Ended the modification to the graphic part, we can proceed with adding the tapped event of the new button Find sample page. I feel F7, entered the code editor we add the code following at once under the event tapped btnDeleteSample_Tapped.

private void btnFindSample_Tapped(object sender, TappedRoutedEventArgs e)
{
    Frame.Navigate(typeof(Finddata));
}

 

Test application

We have finished all the necessary modifications; we can now proceed with the application test. For what we must modify before how see and already explained the compilation target in the first article on ARM platform. We can execute it either from the menu "Build" then choosing" management configuration", or the Toolstrip control selecting the ARM platform from the combobox control. Ended this activity, press key F5 and we start the debug. After the application is started we do tap on Button Insert sample page. Entered the next screen, we insert one or more increasing the value.


Image  1.7 The Insert page screen with the first inserted user.


Image  1.8 The Insert page screen with the second inserted user.


Image  1.9 The Insert page screen with third inserted user.

I have inserted these three users in sequence and their information has been memorized inside the tables Employee and Job inside the database people.db. Ended the data input, we go back to the main screen and do a tap on button Find sample page. When we are in the research screen, will notice that for pre-defined setting the research is selected for name. We leave so the settings and type in inside the TextBox control the name of a user whom we have inserted previously. Ended the insertion, we do a tap on button Find, and if it is found the correspondence when we will be look in the Result screen we will be the information on the user whom we have chosen for the research, we will differently not show anything. I will insert the name "Carmelo", and this and the result of the research.


Image  1.10 The Find screen dates page with the research for name.

    
Image  1.11 The executed research for name Result screen.


Image  1.12 The Find screen dates page with the research for role.


Image  1.13 The executed research for role Result screen.


Image  1.14 The Find screen dates page with the research for age.


Image  1.15 The research for executed age Result screen.

All the possible research combinations have been tried, for name, role and age, with the results which we were expecting in the result screen, everything by the FindForName method which we have inserted in the class DatabaseManagement. There is still a functionality to be tried, that is update of the information which we have inserted. We turn in the main screen, and do a tap Update sample page, entered the screen we will show all the information on the users in the ListBox control. We do a tap on an item and TextBox will be increased the value submitting except for that of the duty as visible in the following figures.


Image  1.16 The Update page screen after the selection of an item on the ListBox control.


Image  1.17 The Update page screen after the modification of the role with Developer value.


Image  1.18 The Update page screen with a MessageDialog of data updating confirmation.


Image  1.19 The Find screen dates page with the selection of research set up for role.


Image  1.20 The finished research Result screen.

And been modified the role from Verniciatore To Developer and have executed a piece of research later specifying in the TextBox control of the Find screen he dates page the term "Developer", and in the Result screen we show the information based on the wished search criteria.

 

Conclusion

In this second part, we have modified the project of the first article according to demands, inserted a new FindForName called method in the class DatabaseManagement, created two new screens, that is Finddata page and Result page, created two classes Job and RoleUser, the first to be able to save all what which regards the user's role, the second to show the research results, at last have seen as execute a piece of research inside the tables in a Sqlite Database moving however in content of the tables in two collections, since how I previously dictate the Sqlite-net does not support all the Linq Extension method and relationships between tables. In the next article will see as is possible insert, remove and bring up to date several data simultaneously, exploiting some of the methods than the bookshop SqliteNet places at disposal of us developers. 

 

Other resources

Another important place to find a huge amount of Windows Phone related articles is the TechNet Wiki itself. The best entry point is   Windows Phone Resources on the TechNet Wiki