Search code examples
c#maskedtextbox

Can anyone tell me what's wrong in this part of code


Its better to accept my mistake with this question. I messed up things thats why i had this problem. Sorry for bothering you people ...

string name = ((DateTimePicker)sender).Name.ToString();
        name = name.Substring(0, name.Length - 1);
        name = name + "4";
        TimeSpan duration = new TimeSpan();
        duration = ((DateTimePicker)sender).Value - ((DateTimePicker)panel2.Controls[name]).Value;
        name = name.Substring(0, name.Length - 1);
        name = name + "6";
        ((MaskedTextBox)panel2.Controls[name]).Text = duration.ToString();

On execution it gives me Object reference not set to instance of an object similar functionality is used on other places but I can't find out what I have to reinitialize here :$

alt text http://www.freeimagehosting.net/uploads/735eefb5db.jpg

The casting for datetimepicker is fine I have to get a name for the datetiempicker to identify the row it's on in my form and the picker before that to calculate their differences and then print that difference in a maskedtext box from the control whose name I make using names of two datetimepickers but when I access controls in the error line I get this message.


Solution

  • Lots...

    Use String.Format() to make this a little clearer. It's OK to not use StringBuilder for this, but it's real hard to understand what you are trying to do.

    Also, things like the

    (DateTimePicker)sender 
    

    Should not be repeated. Cast once, and reuse the cast object.

    DateTimePicker _castObject = (DateTimePicker)sender;
    

    The obj not ref error could be on any of these objects. Unless you step through, or add defensive statements (below), you are going to have a heck of a time figuring it out.

    if (sender == null)
    { throw new ArgumentNullException("sender", "sender is null");}
    

    If this is happening in a standard event handler on your form, it would look something like this (excuse the VB, I cant do c# from memory anymore).

    Protected Function btnOK_Click(sender as Object, e as EventArgs) Handles btnOK.Click
     'your code'
    End Function
    

    If you see something similar, then there is no reason to cast any object on the form. Just access it by its control name (btnOK, txtMaskedTextBox, etc).

    You seem to be going about something here in an entirely wrong way. Perhaps you should start by explaining the actual problem you are trying to solve instead of this specific exception. See "thin metal ruler".