现在,我有挑战将ListView的项目/值保存到数据库中,这是我用来保存项目的代码。
SelectedCategory sc = new SelectedCategory();
SQLiteConnection con = new SQLiteConnection(" Data Source=database.sqlite; Version=3; Compress=True; ");
con.Open();
string query = " INSERT INTO income_details (name, amount) VALUES (@1, @2) ";
for (int i = 0; i < ListView_Selected_Category.Items.Count; i++)
{
SQLiteCommand cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(new SQLiteParameter("@1", ListView_Selected_Category.Items[0]));
cmd.Parameters.Add(new SQLiteParameter("@2", ListView_Selected_Category.Items[0]));
cmd.ExecuteNonQuery();
}
MessageBox.Show("Saved");
con.Close();
因为我无法获取ListView列。
我真的需要帮助,谢谢你。
答案 0 :(得分:0)
如果您正确实现了MVVM模式,那么您将通过视图模型从POCO对象模型中读取ListView(很可能来自已经定义了数据库连接的实体框架工作)
即
ListView ItemSource =&#34; {Binding List}&#34; /&GT;
其中绑定指向名为List
的ObservableCollection并且保存操作就像这样
public void Save_Click(object sender, eventargs args)
{
foreach(var item in List.Where(vm=>vm.IsSelected))
{
item.Save();
}
MessageBox.Show("Saved");
}
和ViewModel是这样的
public class ViewModel
{
public Model Model{get;set;}
public bool IsSelected{get;set;}
public int Val1{get;set;}
public string Val2{get;set;}
public void Save()
{
//Copy ViewModel to Model and trigger Save Logic
}
public void Cancel() //allows undoing
{
//Copy Model to ViewModel
}
}
然后,如果你是在没有EF或其他东西的情况下手动完成的话
public class Model
{
public int Val1{get;set;}
public string Val2{get;set;}
public void Save()
{
SelectedCategory sc = new SelectedCategory();
using(SQLiteConnection con = new SQLiteConnection(" Data Source=database.sqlite; Version=3; Compress=True; "))
{
con.Open();
string query = " INSERT INTO income_details (name, amount) VALUES (@1, @2) ";
SQLiteCommand cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(new SQLiteParameter("@1", Val1);
cmd.Parameters.Add(new SQLiteParameter("@2", Val2);
cmd.ExecuteNonQuery();
}
}
)
注意:如果您想多次使用连接,也可以将其更改为静态函数并传入多个模型