保持ListBox与数据库表同步

时间:2016-07-20 08:54:59

标签: c# wpf database listbox itemssource

我有一个 ListBox listContacts ),我从 Person )填充第一次加载表单时,我的DB( DB1.mdf ):

class Person
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

我如何填写我的列表框:

private void Initiation()
    {
        // Fill list:
        var DB = new Database();
        DataTable Persons = DB.TableFromDB(strMyDBFilePath, "SELECT * FROM Person", "Person");
        var listP = new List<Person>() { };
        foreach (DataRow dr in Persons.Rows)
            //listContacts.Items.Add(dr["Firstname"].ToString().Trim() + " " + dr["Lastname"].ToString().Trim());
            listP.Add(new Person()
            {
                Id = dr["Id"].ToString(),
                Firstname = dr["Firstname"].ToString().Trim(),
                Lastname = dr["Lastname"].ToString().Trim()
            });
        listContacts.ItemsSource = listP;
    }



class Database
{
    public DataTable TableFromDB(string DatabaseName, string Command, string TableName)
    {
        var da = new SqlDataAdapter();
        var ds = new DataSet();
        var cs = new SqlConnection(strSQLNetworkInterface + DatabaseName);
        da.SelectCommand = new SqlCommand(Command,cs);
        da.Fill(ds, TableName);
        return ds.Tables[TableName];
    }

    public void InsertToDB(Person Person, string TableName, string DatabaseName)
    {
        var da = new SqlDataAdapter();
        var ds = new DataSet();
        var cs = new SqlConnection(strSQLNetworkInterface + DatabaseName);
        da.SelectCommand = new SqlCommand("SELECT * FROM " + TableName, cs);

        da.Fill(ds, TableName);
        DataRow dr = ds.Tables[TableName].NewRow();
        dr["Firstname"] = Person.Firstname;
        dr["Lastname"] = Person.Lastname;
        ds.Tables[TableName].Rows.Add(dr);
        var cb = new SqlCommandBuilder(da);
        cb.DataAdapter.Update(ds.Tables[TableName]);
    }
}

当我使用 InsertToDB 向我的 Person )添加记录时,它可以正常工作。我需要的下一件事是更新我的 ListBox listContacts )。我不能只是:

listContacts.Items.Add(pNew.Firstname + " " + pNew.Lastname);

出现此错误:

  

使用ItemsSource时,操作无效。使用ItemsControl.ItemsSource访问和修改元素

现在我的问题:如何使用ItemsSource来保持我的ListBox同步?

修改

基于@Kirenenko的提示,我已经添加了这个:

var listP = (List<Person>)(listContacts.ItemsSource);
listP.Add(pNew);
listContacts.ItemsSource = listP;

但似乎没有更新我的 ListBox

1 个答案:

答案 0 :(得分:0)

基于问题:Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead我做到了这一点:

var listP = (List<Person>)(listContacts.ItemsSource);
listP.Add(pNew);
listContacts.ClearValue(ItemsControl.ItemsSourceProperty);
listContacts.ItemsSource = listP;

为我工作。 谢谢@Kirenenko和@Matthijs H!