在添加或删除数据库中的条目时刷新dataGridView项?

时间:2012-07-04 09:36:47

标签: c# winforms gridview

我在Winforms中添加,删除和更新数据到数据库。我在所有添加,删除和更新表单上都有gridview。 删除单击“删除”按钮后的记录删除记录应立即从dataGridView中删除。

////请注意DATABIND给出错误,即缺少使用或汇编引用。

代码背后:

    private void btnDelete_Click(object sender, EventArgs e)
    {

        if (txtIDD.Text == "")
        {
            MessageBox.Show("Please fill ID no. of record to Delete", "Important Message");

        }
        else
        {
            try
            {
                OleDbCommand Cmd = new OleDbCommand();
                Cmd.Connection = conn;
                conn.Open();
                Cmd.CommandText = "DELETE FROM AddressBook WHERE ID="+txtIDD.Text;
                Cmd.CommandType = CommandType.Text;
                Cmd.ExecuteNonQuery();
                Cmd.Connection.Close();
                conn.Close();
                dataGridView3.Update();
                MessageBox.Show("Delete Succesfull");
            }
            catch (System.Exception err)
            {
                  dataGridView3.DataSource = dt;
                  dataGridView3.DataBind();
                  dataGridView3.Update();

                this.label27.Visible = true;
                this.label27.Text = err.Message.ToString();
            }
        }

    }

2 个答案:

答案 0 :(得分:0)

再次绑定网格,在添加,更新和删除等后从数据库中获取值。

private void btnDelete_Click(object sender, EventArgs e)
{

    if (txtIDD.Text == "")
    {
        MessageBox.Show("Please fill ID no. of record to Delete", "Important Message");

    }
    else
    {
        try
        {
            OleDbCommand Cmd = new OleDbCommand();
            Cmd.Connection = conn;
            conn.Open();
            Cmd.CommandText = "DELETE FROM AddressBook WHERE ID="+txtIDD.Text;
            Cmd.CommandType = CommandType.Text;
            Cmd.ExecuteNonQuery();
            Cmd.Connection.Close();
            conn.Close();                

            **//Call a method that binds the grid or get DataTable from database and bind it like this**
             dataGridView3.DataSource = dt;               
            dataGridView3.Update();

            MessageBox.Show("Delete Succesfull");
        }
        catch (System.Exception err)
        {
            this.label27.Visible = true;
            this.label27.Text = err.Message.ToString();
        }
    }
}

答案 1 :(得分:-2)

创建一个可以重新加载网格的功能

private method ReloadGrid()
{
   // first load your datatable/dt then set it as the datasource of your grid
   dataGridView3.DataSource = dt;
   dataGridView3.DataBind();

}