Winforms DataGridView将添加两行而不是一行

时间:2019-07-05 03:51:27

标签: c# winforms datagridview

当我将数据添加到DataGridView中的一行时,我希望添加空白行。发生这种情况,但是当我关注当前行中的一个字段并且不输入任何数据时,将为该行填充默认值,并且也将使用默认值填充新行。然后再添加一个空白行,如您从下面粘贴的动画gif中所见。

enter image description here

我想看看是否有人可以帮助我确定如何防止空白行以及当前行填充默认值。在当前行中保留一个字段且未输入值之后,可以使用默认值填充该行,但是我不希望任何内容填充空白行。

我从下面的表单类粘贴了相关代码。我试图消除班级中与该问题无关的部分:

public partial class frmCharitableContributions : Form
{
    private readonly string connectionString = ConnectionStringProvider.GetConnectionString();
    private readonly BusinessLayer bl = new BusinessLayer();


    private void FrmCharitableContributions_Load(object sender, EventArgs e)
    {

        PopulateDataGridView();
    }


    private void PopulateDataGridView()
    {
        try
        {
            DataSet dsCharitableContributions = bl.GetCharitableContributions(connectionString);

            CharitableContributionsDataGridView.DataSource = dsCharitableContributions.Tables[0];
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception Thrown in PopulateDataGridView: " + ex.Message);
        }
    }


    private void CharitableContributionsDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (CharitableContributionsDataGridView.CurrentRow != null)
        {
            DataGridViewRow dgvRow = CharitableContributionsDataGridView.CurrentRow;

            bool isValid = ValidateFields(dgvRow);
            if (isValid)
            {
                bl.InsertOrUpdateCharitableContributions(connectionString, dgvRow);
            }
            else
            {
                return;
            }

            BeginInvoke(new MethodInvoker(PopulateDataGridView));
        }
    }

    // This event will fire when a cell recognize editing
    private void CharitableContributionsDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        CharitableContributionsDataGridView.AllowUserToAddRows = false;
    }

    // This event will fire when a cell recognizes the end of editing
    // Allow or deny adding a new row here based on conditions such as required fields being filled in or selected
    private void CharitableContributionsDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        int currentRowIndex = e.RowIndex;
        DataGridViewRow dgvRow = CharitableContributionsDataGridView.Rows[currentRowIndex];
        if (dgvRow.Cells["cbxCharitableOrganizationName"].Value.ToString() != "")
        {

            if (CharitableContributionsDataGridView.CurrentRow != null)
            {


                bl.InsertOrUpdateCharitableContributions(connectionString, dgvRow);

                CharitableContributionsDataGridView.AllowUserToAddRows = true;
            }
        }
    }
}

0 个答案:

没有答案