DataGridView和SqlDataAdapter未正确更新

时间:2012-02-24 19:08:11

标签: c# datagridview bindingsource sqldataadapter

我一直在四处寻找,我无法弄清楚这个问题的来源。发生的事情是我有一个使用BindingSource,SqlDataAdapter,SqlCommandBuilder和DataTable的datagridview。 datagridview使用简单的select查询填充(只使用MSSQL Server DB中的一个表)。我希望能够编辑此表中的内容。现在,编辑工作,但不是应该的方式。我认为我可以编辑一个单元格,按Enter键,并将更改提交给数据库。实际发生的是,在我完成编辑第二个单元格之前,更改不会出现。谁知道我在这里俯瞰什么?谢谢!

以下是.cs文件中的相关代码:

public partial class CheckIn : Form
{

    private BindingSource searchDGVBindingSource = new BindingSource();
    private SqlDataAdapter searchDGVDataAdapter;
    private SqlCommandBuilder searchDGVSqlCommandBuilder;
    private DataTable  searchDGVDataTable;


    public CheckIn()
    {
        InitializeComponent();
        this.Load += new System.EventHandler(CheckIn_Load);
    }

    private void CheckIn_Load(object sender, EventArgs e)
    {
        searchDGV.DataSource = searchDGVBindingSource;
        searchDGVDataAdapter = new SqlDataAdapter(selectCommand, connectionString);
        searchDGVSqlCommandBuilder = new SqlCommandBuilder(searchDGVDataAdapter);
        searchDGVDataTable = new DataTable();
        searchDGVDataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
        searchDGVDataAdapter.Fill(searchDGVDataTable);
        searchDGVBindingSource.DataSource = searchDGVDataTable;

        searchDGV.AutoResizeColumns();
    }

    private void searchGridView_RowEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        searchDGVDataAdapter.Update(searchDGVDataTable);
    }
}

以下是.Designer.cs文件中的相关代码:

        // 
        // searchDGV
        // 
        this.searchDGV.AllowUserToAddRows = false;
        this.searchDGV.AllowUserToDeleteRows = false;
        this.searchDGV.BackgroundColor = System.Drawing.Color.White;
        this.searchDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.searchDGV.Location = new System.Drawing.Point(10, 250);
        this.searchDGV.MultiSelect = false;
        this.searchDGV.Name = "searchDGV";
        this.searchDGV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
        this.searchDGV.Size = new System.Drawing.Size(619, 150);
        this.searchDGV.TabIndex = 7;
        this.searchDGV.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.searchGridView_CellClick);
        this.searchDGV.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.searchGridView_RowEndEdit);

1 个答案:

答案 0 :(得分:2)

您需要在事件处理程序中调用searchDGVBindingSource.EndEdit(),它才能正常工作:

private void searchGridView_RowEndEdit(object sender, DataGridViewCellEventArgs e)
{
    searchDGVBindingSource.EndEdit();
    searchDGVDataAdapter.Update(searchDGVDataTable);
}

检查BindingSource.EndEdit() {{1}}以了解详情。