Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8298921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T15:57:34+00:00 2026-06-08T15:57:34+00:00

I’m designing a windows form with a TabControl that contains 2 tabs. I have

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T15:57:36+00:00Added an answer on June 8, 2026 at 3:57 pm

    @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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a jquery bug and I've been looking for hours now, I can't
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.