datagridview cellvaluedchanged事件在其他datagridview中重用它

时间:2015-10-18 14:01:55

标签: c# datagridview

如何在具有相同功能的其他datagridview中重用cellvaluechanged事件。而不是制作另一个cellvaluechanged事件,我可以重用相同的cellvaluechanged事件。我怎么能这样做?

我从标签页中隐藏了4个具有相同功能的datagridviews。

我的应用程序是一个评分系统,除以4个datagridviews,prelim,midterm,prefinal和final datagridviews。

private void dgvPrelim_CellValueChanged(object sender, DataGridViewCellEventArgs e, DataGridView dgv)
{
    if (dgvPrelimLec.SelectedRows.Count > 0)
    {
        string studentID = dgvPrelimLec.Rows[e.RowIndex].Cells[1].Value.ToString();

        string data;
        var row0 = dgvPrelimLec.Rows[0];

        //if row index zero is selected
        if (row0.Selected)
        {
            if (dgvPrelimLec.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == DBNull.Value)
            {
                data = "null";
            }
            else
            {
                data = dgvPrelimLec.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }

            //attendance
            if (dgvPrelimLec.Columns[e.ColumnIndex].Index >= 3 && dgvPrelimLec.Columns[e.ColumnIndex].Index <= 16)
            {
                int attendanceColumnIndex = dgvPrelimLec.Columns[e.ColumnIndex].Index - 2;
                string AttendanceTableName = "A" + attendanceColumnIndex;

                string sql = string.Format("UPDATE LectureOver SET " + AttendanceTableName + " = ISNULL(" + data + ",null) WHERE studentID= '" + studentID + "' AND subjectID = '" + getSubjectID + "'");
                con.Open();
                cmd = new SqlCommand(sql, con);
                cmd.ExecuteNonQuery();
                con.Close();

                //and so on..... codes

2 个答案:

答案 0 :(得分:1)

dgvPrelimLec替换为currentView

var currentView = (DataGridView)sender;
if (currentView.SelectedRows.Count > 0)
{
    string studentID = currentView.Rows[e.RowIndex].Cells[1].Value.ToString();
    //and so on...
}

并将此处理程序订阅到您的所有视图。

答案 1 :(得分:0)

是。您可以根据需要将多个datagridview绑定到单个事件。您可以在C#代码中绑定下面的那些 -

dgvPrelimLec.CellValueChanged += dgvPrelim_CellValueChanged;
dgvMidterm.CellValueChanged += dgvPrelim_CellValueChanged;
dgvPrefinal .CellValueChanged += dgvPrelim_CellValueChanged;
dgvFinal.CellValueChanged += dgvPrelim_CellValueChanged;



private void dgvPrelim_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dvg = (DataGridView)sender;

        .....
    }