Can I use multiple DataGridViewRows in a single form?

I'm designing a windows form with a TabControl that contains 2 tabs. I have a DataGridView in each tab, and both are populated with the same columns (including a DataGridViewCheckBoxColumn), but different parameters so that it is easier for the end user to work with them, rather than all being contained in 1 grid.

I thought I could set a DataGridViewRow for each DatagridView, and that it would just use them as new instances when called, but that doesn't seem to be the case.

The following code works fine when the user checks or unchecks the check boxes in the first tab's DataGridView;

private void dgvChq_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        int column = e.ColumnIndex;
        int row = e.RowIndex;
        if (column == 5)
        {
            DataGridViewCheckBoxCell c = dgvChq[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell;
            if (c != null)
            {
                string a = e.FormattedValue.ToString();
                if (a == "True")
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Customer.OrderHeader SET DateApproved = @approved WHERE OrderNumber = @ordNo";

                        cmd.Parameters.AddWithValue("@approved", DateTime.Today);
                        cmd.Parameters.AddWithValue("@ordNo",dgvChq.Rows[row].Cells[0].Value.ToString());

                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    DataGridViewRow dr = dgvChq.SelectedRows[0];
                    dr.Cells[4].Value = DateTime.Today.ToString();
                }
                else
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Customer.OrderHeader SET DateApproved = NULL WHERE OrderNumber = @ordNo";

                        cmd.Parameters.AddWithValue("@ordNo", dgvChq.Rows[row].Cells[0].Value.ToString());

                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    DataGridViewRow dr = dgvChq.SelectedRows[0];
                    dr.Cells[4].Value = "";
                }
            }
        }
    }

so I figured I could use a different DataGridViewRow and re-use this code for the other DataGridView in the other tab, but it fails;

private void dgvCredit_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        int column = e.ColumnIndex;
        int row = e.RowIndex;
        if (column == 0)
        {
            DataGridViewCheckBoxCell c = dgvCredit[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell;
            if (c != null)
            {
                string a = e.FormattedValue.ToString();
                if (a == "True")
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Customer.OrderHeader SET DateApproved = @approved WHERE OrderNumber = @ordNo";

                        cmd.Parameters.AddWithValue("@approved", DateTime.Today);
                        cmd.Parameters.AddWithValue("@ordNo", dgvCredit.Rows[row].Cells[1].Value.ToString());

                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    DataGridViewRow dgvr = dgvCredit.SelectedRows[0];
                    dgvr.Cells[4].Value = DateTime.Today.ToString();
                }
                else
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE Customer.OrderHeader SET DateApproved = NULL WHERE OrderNumber = @ordNo";

                        cmd.Parameters.AddWithValue("@ordNo", dgvCredit.Rows[row].Cells[1].Value.ToString());

                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    DataGridViewRow dgvr = dgvCredit.SelectedRows[0];
                    dgvr.Cells[4].Value = "";
                }
            }
        }
    }

Have I missed something here, or is it not possible to use multiple DataGridViewRows in the same form?

Maybe there's a more 'dynamic' way that I could be doing this too, which may help solve my problem?

PS: It seems to be the second datagridviewrow (dgvr) is still showing as null when the check box is clicked, so this is where the error is happening.

Answers


@Keefa2011, The problem is not with DataGridViewRow instances. Agreed they are reference type, so you should be careful when making such instances member variable. But in your code, their scope is limited to a particular event.

The problem lies with the line you mentioned. Unless the FullRowSelect is enabled, you are always going to get an exception at DataGridViewRow dgvr = dgvCredit.SelectedRows[0]; That's 'coz the selected rows count will be always zero. You need to handle that. You can do it either by enabling full row select or by changing that one erroneous line (which is shown below). I am unsure why you get the error only for the second dgv. Perhaps full row select is enabled for the first dgv?

Furthermore, your code is crying for some refactoring. What you have written in two pages is actually just this much:

private void dgvChq_CellValidating(object sender, 
                                   DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex != 5)
        return;

    HandleCheckedChanged(dgvChq, e, 
                         Convert.ToInt32(dgvChq.Rows[e.RowIndex].Cells[0].Value));
}

private void dgvCredit_CellValidating(object sender, 
                                      DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex != 0)
        return;

    HandleCheckedChanged(dgvCredit, e, 
                         Convert.ToInt32(dgvCredit.Rows[e.RowIndex].Cells[1].Value));
}

private void HandleCheckedChanged(DataGridView dgv, 
                                  DataGridViewCellValidatingEventArgs e, int id)
{
    object toBeDisplayedDateValue = (bool)e.FormattedValue ? (DateTime?)DateTime.Today : null;

    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = @"UPDATE Customer.OrderHeader 
                            SET    DateApproved = @approvedDate 
                            WHERE  OrderNumber = @ordNo";

        cmd.Parameters.AddWithValue("@approvedDate", toBeDisplayedDateValue);
        cmd.Parameters.AddWithValue("@ordNo", id);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    dgv.Rows[e.RowIndex].Cells[4].Value = toBeDisplayedDateValue; //you could just do 
                                                                  //this much 
    //or

    //DataGridViewRow dgvr = dgv.SelectedRows[0]; //this line works only if there 
                                                  //is at least one selected row when 
                                                  //validating cell. For this you 
                                                  //require 
                                                  //dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
}

You should actually move the database operation to another class to have a cleaner design. The biggest caveat with your code is where you are passing the id as "@ordNo". I moved it outside the function only 'coz I'm unsure if you should get that value from the UI side. That logic should be handled from the db side. In other words, you should keep the order number somewhere else, possibly as Tag of the dgv row or so. If you are so sure that the value in a gridview cell can actually be accounted for the proper record in database, then go ahead, you need to pass just the column index of order number column as the argument.

Another thing, I dont think you actually need the cell validating event since its fired every time you move focus out of a cell. Since its db operation and can be expensive, you could register the cell value changed event which would do the operation only if the value of the cell is changed. One thing to notice here is that you should register the event only after fully loading all the cells. Otherwise it gets fired even when initially populating the records.

For example,

private void Form1_Load(object sender, EventArgs e)
{
    //---------------------------------------------
    // load dgv...
    //---------------------------------------------

    dgvChq.CellValueChanged += dgvChq_CellValueChanged;
    dgvCredit.CellValueChanged += dgvCredit_CellValueChanged;
}

private void dgvChq_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex != 5)
        return;

    HandleCheckedChanged(dgvChq, e, 0);
}

private void dgvCredit_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex != 0)
        return;

    HandleCheckedChanged(dgvCredit, e, 1);
}

private void HandleCheckedChanged(DataGridView dgv, DataGridViewCellEventArgs e, 
                                  int columnIndexOfOrderNo)
{
    DataGridViewCheckBoxCell c = dgv[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell;
    object toBeDisplayedDateValue = (bool)c.EditedFormattedValue ? (DateTime?)DateTime.Today : null;

    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = @"UPDATE Customer.OrderHeader 
                            SET    DateApproved = @approvedDate 
                            WHERE  OrderNumber = @ordNo";

        cmd.Parameters.AddWithValue("@approvedDate", toBeDisplayedDateValue);
        cmd.Parameters.AddWithValue("@ordNo", 
                                    Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[columnIndexOfOrderNo].Value));

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    dgv.Rows[e.RowIndex].Cells[4].Value = toBeDisplayedDateValue;
}

You should ideally be passing the columnindex of the field to be updated (in your case 4) to the function since these things can be different for dgvs in future easily.


Need Your Help

Android SDK: View Pager not Going Back to Correct View

java android android-viewpager android-preferences

I have a view which can be accessed in 3 ways depending on the users' actions.

Can I solve Silverlight color rendering differences in IE7/8?

silverlight internet-explorer firefox rendering

I have a Silverlight control that tries to have the same background as the underlaying div, but I'm facing color difference problems in IE7/8: