使用数据源更新或刷新

时间:2013-03-16 18:03:42

标签: c# .net winforms listbox

我将数据从ms-access数据库加载到listbox ..我想要做的就是在点击更新按钮时更新或刷新listbox datasource。然后这是我用于方法的代码,然后调用DataLoadListBox()上的form_load event,并更新button_click event ..

private BindingList<mylist> myList = new BindingList<mylist>();

private void DataLoadListBox()
{
    string query = "select * from myItem order by itemname";
    OleDbDataAdapter cmd = new OleDbDataAdapter(query, Conn());
    DataSet dt = new DataSet();
    cmd.Fill(dt, "myItem");
    DataTable datTable = dt.Tables[0];
    foreach (DataRow dtRow in datTable.Rows)
    {
        myList.Add(new mylist() { id = dtRow["ID"].ToString(), itemname = dtRow["itemname"].ToString() });
    }
    mylb.DisplayMember = "itemname";
    mylb.DataSource = myList;
    mylb.ValueMember = "id";
    Conn().Close();
}

然后当textbox文字填满我想要的内容时,我推送了更新button_click事件,其编码如下所示

OleDbCommand comm = new OleDbCommand("update myItem set itemname = @itemname where ID = @ID", Conn());
comm.Parameters.AddWithValue("@itemname", itemname.Text);
comm.Parameters.AddWithValue("@ID", itemid.Text));
comm.ExecuteNonQuery();
// start updating the listbox
myList.Clear();
mylb.DataSource = null;
mylb.Items.Clear();
mylb.Refresh();
mylb.Update();
mylb.DataSource = myList;
DataLoadListBox();
// none of above working, the listbox datasource not getting update

问题是我没有更新我的listbox datasource,我在这里做错了什么?我如何使这项工作?

1 个答案:

答案 0 :(得分:0)

您似乎关闭了DataLoadListBox中的连接。你是在button_click中打开它还是在达到该代码时至少打开它?

如果不是您在此处缺少最少的异常处理。如果ExecuteNonQuery抛出异常,那么你现在只是忽略它。