添加CheckBoxColumn后,DataGridView CellEnter事件显示错误的列索引

时间:2019-02-11 12:15:50

标签: c# winforms datagridview


我是C#的新手。我正在将CheckBoxColumn动态添加到我的datagridview中。但是当我在检查CheckBoxColumn事件的列索引时添加了CellEnter后,它总是显示CheckBoxColumn的索引0。这是我的代码...

private void DefaultGrid(Form frm)
        {
            DataGridView dgv = (DataGridView)frm.Controls.Find("dgvHP_WardChargeMaster_Detail___", true).SingleOrDefault();
            using (DataTable dt = new DataTable())
            {
                dt.Columns.AddRange(new DataColumn[5]
            {
            new DataColumn("Sr", typeof(string)), new DataColumn("Code", typeof(string)), new DataColumn("Description",typeof(string)),
            new DataColumn("Rate",typeof(string)), new DataColumn("Ferquency",typeof(string))});
                dt.Rows.Add("1", "", "", "", "");
                dgv.DataSource = dt;
                dgv.Columns[0].Width = 30;
                dgv.Columns[2].Width = 200;
                dgv.Columns[3].Width = 60;
                dgv.Columns[4].Width = 75;
                dgv.AllowUserToResizeColumns = false;
                dgv.ColumnHeadersDefaultCellStyle.Font = new Font("Cambria", 9, FontStyle.Bold);
                foreach (DataGridViewColumn Col in dgv.Columns)
                {
                    if (Col.Index == 0)
                        Col.ReadOnly = true;
                    else
                        Col.ReadOnly = false;
                    Col.Visible = true;
                    Col.DefaultCellStyle.Font = new Font("Cambria", 9);
                }
                dgv.Columns[1].Visible = false;

                DataGridViewCheckBoxColumn chkHalfRate = new DataGridViewCheckBoxColumn();
                chkHalfRate.Width = 74;
                chkHalfRate.HeaderText = "Half Rate";
                chkHalfRate.Name = "HalfRate";
                chkHalfRate.DisplayIndex = 5;
                dgv.Columns.Add(chkHalfRate);
            }
        }

CellEnter事件

private void dgvHP_WardChargeMaster_Detail____CellEnter(object sender, DataGridViewCellEventArgs e)
        {

                        MessageBox.Show(e.ColumnIndex.ToString());
                        if (e.ColumnIndex == 4)
                        {

                        }

        }

0 个答案:

没有答案