简体   繁体   English

加载数据时未触发Datagridview组合框和文本框事件

[英]Datagridview Combobox and Textbox event not firing when data is loading

I am creating an application in which datagridview having one combobox and multiple textbox 我正在创建一个应用程序,其中datagridview具有一个组合框和多个文本框

In datagridview, when I select manually datagridviewcombobox value, Textbox value is filled 在datagridview中,当我手动选择datagridviewcombobox值时,将填充文本框值

But datagridview is populated by bindingsource and value of datagridviewcombobox get selected but textbox value is empty 但是datagridview由绑定源填充,并且datagridviewcombobox的值被选中,但文本框的值为空

Example as below 例子如下

Combobox value selected by user, Account Name textbox filled 用户选择的组合框值,填写帐户名称文本框 在此处输入图片说明

Combobox value selected by bindingsource(Dynamically), Account Name textbox is Empty 绑定源(动态)选择的组合框值,“帐户名”文本框为空

在此处输入图片说明

Below is my code 下面是我的代码

int journalID = 0;
public Add(int id = 0)
{
     BindControls();
     journalID = id;
}


  private async void BindControls()
  {
     try
     {               
            if (journalID > 0)
            {
                List<JournalAccountViewModel> list = await new JournalModel().GetDetailById(journalID);
                for (int i = 0; i <= list.Count - 1; i++)
                {
                    bindingSource1.Add(list[i]);
                }
            }
            else
            {
                bindingSource1.Add(new JournalAccountViewModel());
                bindingSource1.List.Clear();
            }
            dgvJournal.AutoGenerateColumns = false;
            dgvJournal.AllowUserToAddRows = true;
            dgvJournal.AutoSize = true;
            dgvJournal.DataSource = bindingSource1;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Rule", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }


   private void dgvJournal_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        try
        {
            if (dgvJournal.CurrentCell.ColumnIndex == dgvJournal.Columns[colCredit.Name].Index) //Desired Column
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(txtNumeri_KeyPress);
                }
            }

            if (dgvJournal.CurrentCell.ColumnIndex == dgvJournal.Columns[ColDebit.Name].Index) //Desired Column
            {
                TextBox tb = e.Control as TextBox;
                if (tb != null)
                {
                    tb.KeyPress += new KeyPressEventHandler(txtNumeri_KeyPress);
                }
            }


            ComboBox combo = e.Control as ComboBox;
            if (combo != null)
            {
                combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
                combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Rule", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }


   private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (((ComboBox)sender).SelectedItem != null)
            {
                AccountViewModel account = (AccountViewModel)((ComboBox)sender).SelectedItem;
                var currentcell = dgvJournal.CurrentCellAddress;
                DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dgvJournal.Rows[currentcell.Y].Cells[ColAccountName.Name];
                cel.Value = account.Name;
            }
            else
            {
                ((ComboBox)sender).SelectedIndex = 0;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Rule", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

  private void txtNumeri_KeyPress(object sender, KeyPressEventArgs e)
    {
        try
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Rule", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Please suggest me how to get textbox value filled when combobox value is set programmtically. 请建议我以编程方式设置组合框值时如何填充文本框值。

I would create a CellValueChanged event for that DataGridView and copy over the functionality from your ComboBox_SelectedIndexChanged event. 我将为该DataGridView创建一个CellValueChanged事件,并从您的ComboBox_SelectedIndexChanged事件复制该功能。 This would eliminate the need to set those events in dgvJournal_EditingControlShowing and also resolve your original issue since it will fire anytime a value is changed in the AccountNumber field. 这样就无需在dgvJournal_EditingControlShowing中设置这些事件,并且还可以解决您的原始问题,因为每当AccountNumber字段中的值更改时,它都会触发。

    private void dgvJournal_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        int accountNumberColIndex = dgvJournal.Columns["AccountNumber"].Index;

        // Checking that this value is from the account number column
        if (e.ColumnIndex == accountNumberColIndex)
        {
            AccountViewModel account = (AccountViewModel) dgvJournal.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
            int accountNameColIndex = dgvJournal.Columns["AccountName"].Index;

            DataGridViewTextBoxCell accountNameCell = (DataGridViewTextBoxCell) dgvJournal.Rows[e.RowIndex].Cells[accountNameColIndex];
            accountNameCell.Value = account.Name;
        }
    }
    private void dgvJournal_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        if (e.ListChangedType == ListChangedType.Reset)
        {
            var a = (DataGridView)sender;
            var b = a.DataSource;
            var c = (BindingSource)b;
            var d = c.List;
            int sumDebit = 0, sumCredit = 0;
            int cnt = 0;
            foreach (JournalAccountViewModel account in d)
            {
                dgvJournal.Rows[cnt].Cells[ColAccountName.Name].Value = accountList.Where(acc => acc.ID == account.AccountID).FirstOrDefault().Name;
                enableCell(((DataGridViewCell)dgvJournal.Rows[cnt].Cells[ColDebit.Name]), (account.Debit > 0));
                enableCell(((DataGridViewCell)dgvJournal.Rows[cnt].Cells[colCredit.Name]), (account.Credit > 0));
                cnt++;
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM