How to update specific data into SQLite in Xamarin

强颜欢笑 提交于 2021-02-11 08:10:04

问题


I have created a database using SQLite which store student details including

Student Name (String)
Student Password (String)
Student ID (String)
Student Attendance(Boolean)

In my solution, there are 3 view controller as describe below:

ViewController1 : Table View, Display List of Students.

ViewController2 : Normal View Controller with 3 text field and 1 switch button to get all 4 user detail.

ViewController3 : A button that enable user to tap, and turn the attendance (boolean) to on.


I would like to update a specific student (eg. StudentName = Apple) data using ViewController3's button.

To insert new student data, code should be like this: *(By default, the Attendance is "false")

void SaveButton_Clicked(object sender, EventArgs e)
{
    using (var connection = new SQLite.SQLiteConnection(pathToDatabase))
    {
        connection.Insert(new Student() { StudentName = AddStuNameTxt.Text, StudentId = AddStuIdTxt.Text, StudentPassword = AddStuPassTxt.Text, StudentAttendence = false});
        new UIAlertView("Updated !", "Student successfully created", null, "OK", null).Show();
    }
}

But if I want to update the "Attendance"(Boolean) to true in ViewController3 where student named is "Apple". May i know how to do that?


回答1:


Use code below, Where ever you need like inside button click event. But I would suggest you do this using StudentId instead of StudentName.

//get specific student record
var studentItem=GetSingleRecord("Apple")
studentItem.Attendance=true; 

//update record afermodification   
UpdateContact(studentItem)

Above used method look like this.

public Student GetSingleRecord(string Name)
{
  return connection.Table<Student>().FirstOrDefault(i => i.StudentName == Name);
}

public void UpdateContact(Student obj)
{
    connection.Update(obj);
}


来源:https://stackoverflow.com/questions/51906245/how-to-update-specific-data-into-sqlite-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!