Datagrid view Exception error after datatable update

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • newbtemple
    New Member
    • Feb 2008
    • 31

    Datagrid view Exception error after datatable update

    I keep getting index out of range errors when updating values in a datatable. Please see code below and offer any suggestions on a solution. In general, if the updates are slow, the datagridview does not throw exceptions. When the updates are more frequent, exceptions get thrown.

    I've tried several different methods of updating the datagridview, as can be seen in the code. Any suggestions would be greatly appreciated.

    Code:
            public Form1()
            {
                InitializeComponent();
            }
    
    
            DataTable myDT;
    
            private void button1_Click(object sender, EventArgs e)
            {
                procDGVTEST();
    
    
    
            }
    
    
    
    
            private void procDGVTEST()
            {
    
                myDT = new DataTable();
    
                string strConn = "Server ...Integrated Security=True;";
                string strCMD = "Use TestResults select * from test";
    
                SqlConnection mycn = new SqlConnection(strConn);
                SqlDataAdapter myda = new SqlDataAdapter(strCMD,mycn);
    
    
                myda.Fill(myDT);
                myDT.TableName = "myDT";
    
                //set datasource to datatable directly doesn't Work
                //dataGridView1.DataSource = myDT;
    
                //use a binding source - doesn't Work!
                //BindingSource bSource = new BindingSource();
                //bSource.DataSource = myDT;
                //dataGridView1.DataSource = bSource;
    
                //use dataview doesn't work
                //DataView view = new DataView(myDT);
                //dataGridView1.DataSource = view;
    
    
                DataSet myDS = new DataSet();
                myDS.Tables.Add(myDT);
                dataGridView1.DataSource = myDS;
                dataGridView1.DataMember = "myDT";
    
    
                dataGridView1.AutoGenerateColumns = false;
                
    
    
            }
    
            private void procCounter()
            {
    
                for (double i = 0; i < 1200000000000; i++)
                {
    
                    int updateN = 5000;
                    if ((i % updateN) == 0)
                    {
                        //try
                        //{
                            //myDT.Rows[0][2] = i;
                            //dataGridView1.Rows[0].Cells[2].Value = i;
                        this.dataGridView1[2, 0].Value = i;
                        //}
                        //catch (Exception e)
                        //{
                        //    MessageBox.Show(e.ToString());
                        //}
                    }
                }
    
    
    
            }
    
            private delegate void myDel();
    
            private void button2_Click(object sender, EventArgs e)
            {
    
                //myDel del = new myDel(procCounter);
    
                //del.Invoke();
    
                Thread myThread = new Thread(new ThreadStart (procCounter));
                myThread.Start();
    
            }
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    I can make some general suggestions that apply to good coding practice.
    • Assume that everything is broken, or at least not ideal.
    • Presume that the user is going to provide data in a format or manner that you just didn't expect. If you use a textbox for a number, the user will type "One".
    • Assume that hardware breaks in the middle of what you are doing, so you have to recover.
    • Take a few extra lines of code to get standards like the boot drive, the number thousands seperator etc. Don't assume that you have a C: drive or that a comma is the separator because not everyone is in America.
    • Check that files/folders exist, even if you just did a call to make it: You may not have permissions.
    • Don't assume the harddrive has room for what you are doing: They do fill up. Usually right in the middle of you writing to your log file.
    • Get used to placing breakpoints and walking through the code line by line. Double check EVERYTHING on every line. Keep the "Locals" and "Autos" windows open so you can see your values.
      • Put a breakpoint on the first line of the method causing trouble.
      • When the code stops there, walk through line by line with F-10.
      • Check the values of your assumptions (looking at the Locals and Automatic variable windows as well as hovering the mouse over the variables in the code (hothelp will popup).
    • Stop. Breath. Relax. Then reason out the problem. Cut it down by sections or halves. "The value was good here, then at this method it wasn't. Where did it go between 'A' and 'B'?"
    • Range check and validate values. Confirm that you didn't get a zero when you are only set to accept 1-10. Confirm your objects and values aren't null. Initialize them to a known default if possible. If a selection can be from 0-10, then initialize to -1: Now you have something to check for.


    Example:
    Code:
    Graphics g = Graphics.FromImage(m_Undo);
    Presumes that m_Undo must be good (not null)(actually exists)(not in use)(you have permissions)(do esn't time out when accessed). If that assumption fails so does the program, because you can't make anything from a file if the file is null. Get used to validating data and assumptions in your code if you want it to be robust. For example:
    Code:
    if (m_Undo != null)
    {
       bool bSuccess = false;
       // Do your thing here, for example:
       if (myObject != null) bSuccess = true;
       // or
       if (denominator > 0) bSuccess = true;
       // or
       if (MyFunctionReturn != Failed) bSuccess = true;
       // Hurray, your thing worked!
    
       if (bSuccess)
       {
          // Then do this other thing if it worked
       }
       else
       {
          // Then do the failure recovery part / user failure message
       }
    
       return bSuccess; // If you want the calling method to know if it worked.
    }

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      You did not tell us where you get the index out of range error (which line).
      But I would guess it is in this method
      Code:
              private void procCounter()
              { 
                  for (double i = 0; i < 1200000000000; i++)
                  { 
                      int updateN = 5000;
                      if ((i % updateN) == 0)
                      {
                          //try
                          //{
                              //myDT.Rows[0][2] = i;
                              //dataGridView1.Rows[0].Cells[2].Value = i;
                          this.dataGridView1[2, 0].Value = i;
                          //}
                          //catch (Exception e)
                          //{
                          //    MessageBox.Show(e.ToString());
                          //}
                      }
                  } 
              }
      Just guessing here... What if your datagridview doesn't have an element at [2, 0]? Maybe you should check if it exists before you try to assign a value to it.

      Is it possible this was meant to be [0, 2]? Guest a guess based on the code you have commented out where you set the size.

      Also, keep in mind these things are zero indexed. If you want the 2nd element then you want index 1 [1 , 0] or [0, 1] depending on the row or column.

      Comment

      • newbtemple
        New Member
        • Feb 2008
        • 31

        #4
        Thank you for your reply. This section:

        Code:
        # //myDT.Rows[0][2] = i;
        #                         //dataGridView1.Rows[0].Cells[2].Value = i;
        #                     this.dataGridView1[2, 0].Value = i;
        Are three different ways I tested updating the datagridview. Both the myDT.Rows[0][2] and dataGridView1[2,0] point to the same location. That cell has data.

        All three of the attempts listed here work for a little bit of time. The exception that is thrown occurs as a message box and the counter continues to increment. I'm not sure what line is forcing this exception.

        The increment cell does not seem to get affected. I think that the datagridview control is throwing out the error.

        I created a new method:
        Code:
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
                {
                    //MessageBox.Show("Row:  " + e.RowIndex + "\r\n " + "Column:  " + e.ColumnIndex + "\r\n" + e.ToString() + "\r\n");
        
                    textBox1.AppendText("Row:  " + e.RowIndex.ToString() + "\r\n" + "Column:  " + e.ColumnIndex.ToString() + "\r\n" + e.ToString() + "\r\n" + e.Context.ToString() + "\r\n" + e.ThrowException.ToString() + "\r\n");
        
                }
        The output is:

        Row: 0
        column 2
        System.Windows. Forms.DataGridV iewDataErrorEve ntArgs
        Display
        False

        Comment

        Working...