Click here to Skip to main content
16,017,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have created a local data base but i don't know how to call it by clicking on the button.
XML
    <Button x:Name="CreateDBbutton" Grid.Row="0" Content="Create Local Database" HorizontalAlignment="Center" VerticalAlignment="Top" Click="button_Click" Height="32" />

    <Button x:Name="create" Grid.Row="1" Content="Create New Students" HorizontalAlignment="Center" Click="create_Click"></Button>

    <Button x:Name="read" Grid.Row="2" Content="Read Students List" Width="300" Click="read_Click" HorizontalAlignment="Center"></Button>

    <Button x:Name="update" Grid.Row="3" Content="Update Details" Width="300" Click="update_Click" HorizontalAlignment="Stretch"></Button>

    <ListView x:Name="allstudents" HorizontalAlignment="Stretch" Grid.Row="4">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock x:Name="ee" Text="{Binding Name}" FontSize="14"></TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

C#
public MainPage()
        {
            this.InitializeComponent();
           
        }
        public static void CreateDatabase()
        {
            var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Studentdb.sqlite");
            using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
            {
                conn.CreateTable<Students>();
            }
        }
                }
            }
        }

//(i don't know how to call this button what code should i need to write to create a database by clicking on this button)    
  private void button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void create_Click(object sender, RoutedEventArgs e)
        {

        }

        private void read_Click(object sender, RoutedEventArgs e)
        {

        }

        private void update_Click(object sender, RoutedEventArgs e)
        {

        }
    }


//for more details you can see the link which i have provided below.

What I have tried:

C#
namespace test_1
{
    public class Students
    {
        [SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement]
        public int Id
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Mobile
        {
            get;
            set;
        }
        public Students()
        { }
        public Students(string name, string address, string mobile)
        {
            Name = name;
            Address = address;
            Mobile = mobile;
        }
    }
}


from this blog i took the codeLocal Database SQLite For Windows 10[^]
Posted
Updated 14-Oct-22 4:56am
v4
Comments
Richard MacCutchan 12-Oct-22 9:47am    
You could ask the person who wrote the blog. Alternatively, please explain exactly what the problem is.
Venki Vky 13-Oct-22 1:13am    
i have tried it but the person is not avaiable its very old blog i think he didn't notice any of the questions.in the comment
Richard MacCutchan 13-Oct-22 3:12am    
You still have not explained what the problem is.
Venki Vky 14-Oct-22 1:28am    
now i have updated please tell me the answer if you know .i have attaached the link also .if you stil can't understand copy the code and run it.you can figure it out the doubt which i have been faceing
Richard MacCutchan 14-Oct-22 3:16am    
I have looked again at the tutorial you are following, and it includes all the code that you need. So I am still confused as to what your actual problem is.

You need to call the code that is provided in the blog i.e.
C#
private void button_Click(object sender, RoutedEventArgs e)
{
     CreateDatabase();
}
I advise you rename the event handler to something more meaningful e.g.
XML
<Button x:Name="CreateDBbutton" Grid.Row="0" Content="Create Local Database" HorizontalAlignment="Center" VerticalAlignment="Top" Click="createDBbutton_Click" Height="32" />
and
C#
private void createDBbutton_Click(object sender, RoutedEventArgs e)
{
     CreateDatabase();
}
 
Share this answer
 
Comments
Venki Vky 14-Oct-22 7:51am    
thank you CHill60 i will try it and let you know
I have followed the article (link in the question), added the code and the button click handlers. The SQLite installation details are incorrect so I had to install the correct package and change the code to reflect that.

My tests run to completion but do nothing apart from creating the database. I then added the code to insert some student records and that also works correctly. I was only able to verify the success by running the sqlite3 program from a terminal window.

So for someone with very little knowledge of UWP, .NET and C# This article will not really help, as there are too many things in it which are wrong and/or missing.

[edit]
Adding a working solution based (loosely) on the original article.

1. Create a new UWP Blank page application in Visual Studio.
2. Replace the content of MainPage.xaml and MainPage.xaml.cs with the relevant parts below.
3. Add a new class named Students, and replace the text with the content of Students.cs below.
4. From the Visual Studio menu tabs Select Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution.
5. Use the "Browse" tab and search for "SQLite.Core.UAP" and install it to the project.
6. Search for "sqlite-net-pcl" and install that to the project.

If you have done that all correctly it should now build and you can run it by clicking <Ctrl+F5>.

MainPage.xaml
XML
<Page
    x:Class="Students.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Students"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Page.Resources>
        <Style x:Name="ColumnItemBorder" TargetType="Border">
            <Setter Property="BorderBrush" Value="Gray" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="Margin" Value="5, 0, 5, 0" />
        </Style>
    </Page.Resources>
    <Grid Margin="5, 15, 5, 5">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <CommandBar  Grid.Row="0">
            <AppBarButton x:Name="init" Icon="NewWindow" Label="New" ToolTipService.ToolTip="Initialize" Click="create_Click"/>
            <AppBarButton x:Name="add" Icon="Add" Label="Add" ToolTipService.ToolTip="Add" Click="insert_Click" />
            <AppBarButton x:Name="read" Icon="ViewAll" ToolTipService.ToolTip="View all" Label="Read All" Click="read_Click"/>
            <AppBarButton x:Name="update" Icon="Edit" ToolTipService.ToolTip="Update" Label="Update" Click="update_Click" />
        </CommandBar>
        <ListView x:Name="allstudents" HorizontalAlignment="Stretch" Grid.Row="1">
            <ListView.HeaderTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="120" />
                            <ColumnDefinition Width="120" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Margin="15 0 0 0" Grid.Row="0" Grid.Column="0" Foreground="#ff0000" Text="Id"  />
                        <TextBlock Margin="15 0 15 0" Grid.Row="0" Grid.Column="1" Foreground="#ff0000" Text="Name" />
                        <TextBlock Margin="15 0 15 0" Grid.Row="0" Grid.Column="2" Foreground="#ff0000" Text="Address" />
                        <TextBlock Margin="15 0 15 0" Grid.Row="0" Grid.Column="3" Foreground="#ff0000" Text="Mobile" />
                    </Grid>
                </DataTemplate>
            </ListView.HeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="120" />
                            <ColumnDefinition Width="120" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Margin="7 0 0 0"  Grid.Row="0" Grid.Column="0" Foreground="DarkBlue" Text="{Binding Id}"/>
                        <TextBlock Margin="7 0 15 0" Grid.Row="0" Grid.Column="1" Foreground="DarkBlue" Text="{Binding Name}" />
                        <TextBlock Margin="7 0 15 0" Grid.Row="0" Grid.Column="2" Foreground="DarkBlue" Text="{Binding Address}" />
                        <TextBlock Margin="7 0 15 0" Grid.Row="0" Grid.Column="3" Foreground="DarkBlue" Text="{Binding Mobile}" />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

MainPage.xaml.cs
C#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Xml.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Students
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        Students students;
        string dbname = "Studentdb.sqlite";
        public MainPage()
        {
            this.InitializeComponent();
            students = new Students();
        }

        private void create_Click(object sender, RoutedEventArgs e)
        {
            students.Initialize(dbname, true);
        }

        private void insert_Click(object sender, RoutedEventArgs e)
        {
            Student[] newstudents = {
                new Student("Harold", "LONDON", "07966-513229"),
                new Student("Sadie", "GLASGOW", "07981-277438"),
                new Student("David", "NEW YORK", "+1-431-7438"),
                new Student("Aristotle", "ATHENS", "+30-21-1234567"),
                new Student("Carlo", "ROME", "+39-3987654321")
            };
            foreach (Student student in newstudents)
            {
                students.Add(student);
            }
        }
        private void read_Click(object sender, RoutedEventArgs e)
        {
            List<Student> studentlist = students.ReadAll();
            ObservableCollection<Student> studentCollection = new ObservableCollection<Student>(studentlist);
            allstudents.BorderThickness = new Thickness(3);
            allstudents.BorderBrush = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Black);
            allstudents.ItemsSource = studentCollection;
        }

        private void update_Click(object sender, RoutedEventArgs e)
        {
            students.Update(3, null, "LOS ANGELES", "+1-345-7811");
        }
    }
}

Students.cs
C#
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace Students
{
    internal class Students
    {
        string sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Studentdb.sqlite");

        public Students()
        {
        }

        public void Initialize(string database, bool create = false)
        {
            sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, database);
            if (create)
            {
                using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
                {
                    connection.DropTable<Student>();
                    connection.CreateTable<Student>();
                }
            }
        }

        public void Add(Student student)
        {
            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
            {
                connection.RunInTransaction(() =>
                {
                    connection.Insert(student);
                });
            }
        }

        public void Update(int studentid, string name, string address, string mobile)
        {
            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
            {
                var existingstudent = connection.Query<Student>("SELECT * FROM Student WHERE Id =\"" + studentid + "\"").FirstOrDefault();
                if (existingstudent != null)
                {
                    if (name != null)
                        existingstudent.Name = name;
                    if (address != null)
                        existingstudent.Address = address;
                    if (mobile != null)
                        existingstudent.Mobile = mobile;
                    connection.RunInTransaction(() =>
                    {
                        connection.Update(existingstudent);
                    });
                }
            }
        }

        // Retrieve the specific contact from the database.    
        public Student Read(int studentid)
        {
            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
            {
                var existingstudent = connection.Query<Student>("SELECT * FROM Student WHERE Id =" + studentid).FirstOrDefault();
                return existingstudent;
            }
        }

        public List<Student> ReadAll()
        {
            List<Student> studentList = null;
            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
            {
                studentList = connection.Table<Student>().ToList<Student>();
            }
            return studentList;
        }

        public void DeleteContact(int Id)
        {
            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(sqlpath))
            {
                var existingstudent = Read(Id);
                if (existingstudent != null)
                {
                    connection.RunInTransaction(() =>
                    {
                        connection.Delete(existingstudent);
                    });
                }
            }
        }
    }

    internal class Student
    {
        [SQLite.PrimaryKey, SQLite.AutoIncrement]
        public int Id
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Mobile
        {
            get;
            set;
        }
        public Student()
        { }
        public Student(string name, string address, string mobile)
        {
            Name = name;
            Address = address;
            Mobile = mobile;
        }
    }
}


[edit]
 
Share this answer
 
v3
Comments
Venki Vky 18-Oct-22 1:09am    
ya your code is working but there are some error in this code like debugger error so can you give me the article. which you had reffered
Richard MacCutchan 18-Oct-22 2:38am    
There is no new article; as I already said, I took the code from the article you referred to. There were too many things wrong or missing in it. So I rewrote parts of it to make it follow the OOP model better, and to clarify what the code was (supposed to be) doing. So if you have problems with it you need to explain exactly what those problems are and where they occur.
Venki Vky 18-Oct-22 3:17am    
So its you code you took the article as reference its great to hear :-) you code is running prety good but only view all button is working . you have gave the code for the other two button like add,update but the button its not working can you check your code once again . your code in that two button is very good but its not working .
Richard MacCutchan 18-Oct-22 3:21am    
You need to explain what you mean by "not working". All the buttons work for me - that is to say they do what the code says.
Venki Vky 18-Oct-22 3:31am    
the add button is not working. what function did you given in add button the code is working but the function which you have given in add button is not working

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900