Search code examples
c#sharepoint-2010nullreferenceexception

How can I overwrite a LiteralControl's text only if the LiteralControl has not already had text assigned to it?


This code:

private void btnSave_Click(object sender, EventArgs e)
{
    LiteralControl message = null;
    try
    {
        message = new LiteralControl();
        Controls.Add(message);
        ConditionallyCreateList();
        SaveInputToList();
        List<ListColumns> listOfListItems = ReadFromList();
        GeneratePDF(listOfListItems); // using iTextSharp
    }
    catch (Exception ex)
    {
        message.Text = String.Format("Exception occurred: {0}", ex.Message);
    }
    if (message.Text.Length <= 1)
    {
        message.Text = "Saving the data and converting it to a PDF has been successful";
    }
}

...results in a NRE, complaining on the "if (message.Text.Length <= 1)" line. What I'm trying to accomplish is only assign to message's text value if it does not already contain an exception message.


Solution

  • You need message in both the success and the failure branches of the try, so you need to create it ahead of time:

    private void btnSave_Click(object sender, EventArgs e)
    {
        LiteralControl message = new LiteralControl();
        try
        {
            Controls.Add(message);
            ConditionallyCreateList();
            SaveInputToList();
            List<ListColumns> listOfListItems = ReadFromList();
            GeneratePDF(listOfListItems); // using iTextSharp
            message.Text = "Saving the data and converting it to a PDF has been successful";
        }
        catch (Exception ex)
        {
            message.Text = String.Format("Exception occurred: {0}", ex.Message);
        }
    }