开发者

Getting Null exception error in loop. Trying to debug

Im having some problems parsing a string to a textbox type, im using the code in a diffrent form in the program and its working fine, but when im tying the same two lines here i get a null exception

the two lines of intrest is

string txbName = "br" + bruker + "txt" + 'B' + o;
txtBCont = (TextBox)Controls[txbName];

new info

Greg put me in the direction to check waht was inside the Controls[] array and this reveals what my problem is. It only contains 90 lines of TabControl info.

this is the line

System.Windows.Forms.TabControl, TabPages.Count: 2, TabPages[0]: TabPage: {ShowWeek}

this line is dublicated 90 times when i run this code inside my catch block

                catch( System.Exception excep)
                {
                    System.IO.StreamWriter SW;
                    SW = File.AppendText("C:\\MyDumpFile.txt");

                    foreach (Control ctrl in Controls)
                    {
                        SW.WriteLine(ctrl);
                    }
                    SW.Close();
                }

how can this be isen't the Controls array populated on Initialize?


Orginal post

and this is the full loop

        int dayOfset;
        int bruker;

        TextBox txtBCont;

        for (int i = 0; i < 18; i++)
        {
            mysqlCon.Open();
            dayOfset = -4;
            bruker = i + 1;

            for (int o = 1; o < 6; o++)
            {
                MySqlCommand cmd = new MySqlCommand("SELECT  (NyeSaker + GamleSaker - (select GamleSaker FROM saker Where Dato = '" + dateTimePicker1.Value.AddDays(dayOfset + 1).ToString("yyyy-MM-dd") + "' AND Bruker_ID = '" + bruker + "' ) ) FROM saker Where Bruker_ID = '" + bruker + "' AND Dato = '" + dateTimePicker1.Value.AddDays(dayOfset).ToString("yyyy-MM-dd") + "'", mysqlCon);

                string txbName = "br" + bruker + "txt" + 'B' + o;

                txtBCont = (TextBox)Controls[txbName];

                //1   past og dp kontrol//
                try
                {
                    txtBCont.Text = cmd.ExecuteScalar().ToString();
                }
                catch( System.Exception excep)
                {
                    //txtBCont1.Text = "0";   
                    MessageBox.Show(excep.Message);
     开发者_JS百科           }
                dayOfset++;
            }
            mysqlCon.Close();
        } 

in trying to debug it i did this

string txbName = "br" + bruker + "txt" + 'B' + o;
txtBCont = br1txtB1;
txtBCont = (TextBox)Controls[txbName];

and what happens is it sets the txtBCont to Textbox on this line txtBCont = br1txtB1; but on the txtBCont = (TextBox)Controls[txbName]; it sets it back to null again.

anyone got a clue what the error is here?


When attempting to pull something out of a hash or dictionary you will get a null back if it doesnt exist. In this case a Control by the name you are looking for does not exist. I notice your second loop index starts at 1:

for (int o = 1; o < 6; o++) 

Is it possible you are off by 1 and the control does not exist?


Set a breakpoint at the line MessageBox.Show(excep.Message); and run the code.

Check the value of txtBCont using the debugger.
Check the Name properties of all of the items in Controls using the debugger.

Is your assumption that there are controls where bruker >= 0 and <= 17 true?
Is your assumption that there are controls where o >= 1 and <= 6 true?

Edit: this code (or something close it to it) should print out the Name of all the textboxes so you can double check.

foreach( Control ctrl in Controls )
{
  TextBox textBox = ctrl as TextBox;
  if( textBox != null )
    Console.WriteLine( textBox.Name );
}

Edit 2:

I'm assuming you're using a Windows Forms project. The problem is that controls aren't in an array, they're in a hierarchy. The TabControl has its own Controls property that contains TabPages. Each TabPage has its own Controls collection...etc.

The Find method on the Controls property can perform a recursive search on this hierarchy. Unfortunately it can return more than one control, so you need to account for that. In the code below, I've made the assumption that only one control with the request name can exist on the form, and I've thrown an exception if it doesn't.

        Control[] matchingControls = Controls.Find(txbName , true); // true means recursive search

        if (matchingControls.Length == 0 || !(matchingControls[0] is TextBox) )
            throw new InvalidOperationException("No TextBoxes with name " + txbName + " found in the form.");

        if (matchingControls.Length > 1)
            throw new InvalidOperationException("Multiple controls with name " + txbName + " found in the form. Please use unique names");

        txtBCont = (TextBox)matchingControls[0];

Note: I'm not really sure if InvalidOperationException is the best choice here....


Is it possible that the string built up in txbName doesn't exist in the Controls array? Controls[txtbName] may not exist, and therefore would return null.


Try

string txbName = string.Format("br{0}txt'{1}'{2}", bruker, "B", o);


I wouldn't open and close your connection each time within the loop, open it before the loop and close it after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜