views:

105

answers:

5

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);
                }
                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?

+1  A: 

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.

Nick
maybe, how wold i go about fixing that?
Darkmage
If a control with that name doesn't exist, then you need to check for it. You should be able to use Controls.Contains or something similar to make sure that it exists prior to grabbing it.
Nick
+1  A: 
Partha Choudhury
no still getting the same error but had to clean up the ' in the '{1}' thx for answering tho.
Darkmage
+2  A: 

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?

Brian Leahy
i did this to prove that the boxname do exsist. txtBCont = br1txtB1; and that builds fine.im starting the loop at 1 to save one variable when building the sting name.string name is br1txtB1
Darkmage
+1  A: 

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

ck
good point will move it.
Darkmage
+1  A: 

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

Greg
thx you for tips looking in to this now.
Darkmage
the 0 - 17 range is the number of users yesand 1 - 6 range is the 1-2-3-4-5 days of a week, and im using the o to set the textbox name.
Darkmage
oki this seems to be where the error is, after trying to print out what is in controls i find none Textboxes. im updating my findings in the top
Darkmage
thx Greg,you are very helpfull ill try to implement this tomorow when i get back in to work.
Darkmage
Very nice, this worked just fine. Thank you very much for your help an making me understand this better..
Darkmage
You're welcome.
Greg