DataGridViewComboBoxColumn事件触发太多次

时间:2020-10-15 21:06:01

标签: c# winforms datagridcomboboxcolumn

在下拉组合中选择一个值后,我无法停止第二次触发事件。该事件将打开一个对话框,告诉用户是否要使用yes或no选项进行保存。

我有一个网格视图,上面有2列:

我的代码在下面。

nest <- tibble(nest_lat = rnorm(50, n = 2220),
               nest_long = rnorm(50, n = 2220))

landmark <- tibble(mark_lat = rnorm(50, n = 26),
                   mark_long = rnorm(50, n = 26))

当我在第一行的下拉菜单中单击一个新值时,该事件将按预期触发: enter image description here

当我单击“是”时,对话框消失了,但是下拉菜单仍然看起来像已被选中,因为它看起来与其他对话框不同: enter image description here

一旦我尝试选择另一个下拉箭头,它就会像未聚焦一样再次被触发。 enter image description here

在第一个对话框中单击“是”后,如果聚焦,该如何停止?

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案。我同时使用CellValueChanged和CurrentCellDirtyStateChanged使其工作。我的代码在下面。

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        List<Team> teamList = new List<Team>();
        List<Team_Colour> teamColourList = new List<Team_Colour>();
        DataGridViewComboBoxColumn cb = new DataGridViewComboBoxColumn();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            teamList.Add(new Team { name = "Test A", Colour_ID = 1});
            teamList.Add(new Team { name = "Test B", Colour_ID = 2 });
            teamList.Add(new Team { name = "Test C", Colour_ID = 3 });
            teamList.Add(new Team { name = "Test D", Colour_ID = 4 });

            dataGridView1.DataSource = teamList;
            dataGridView1.Columns[1].Visible = false;
            cb.HeaderText = "Colour";

            teamColourList.Add(new Team_Colour { Colour_ID = 1, Colour_Name = "None" });
            teamColourList.Add(new Team_Colour { Colour_ID = 2, Colour_Name = "Green" });
            teamColourList.Add(new Team_Colour { Colour_ID = 3, Colour_Name = "Blue" });
            teamColourList.Add(new Team_Colour { Colour_ID = 4, Colour_Name = "Red" });


            cb.DataSource = teamColourList;
            cb.DisplayMember = "Colour_Name";
            cb.ValueMember = "Colour_ID";
            cb.DataPropertyName = "Colour_ID";


            dataGridView1.Columns.Insert(1, cb);

        }

        private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            DialogResult dialogResult = MessageBox.Show("Are you sure", "Saving", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {

            }
            else if (dialogResult == DialogResult.No)
            {

            }
        }
    }
}