Thursday, March 29, 2012

Newbie -- what are these errors -- System.NullReferenceException

I am new to .NET and C#. I am deploying the SPS web part that appears below
and I am getting System.NullReferenceException in my CreateChildControls
method. The last item shown by my debugger prior to the exception is
"Setting ID."

Any assistance would be greatly appreciated.

Joe Mack

-----
CODE
-----
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Data;

namespace adSearch
{
/// <summary>
/// Description for WebPart1.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:adSearchWP runat=server></{0}:adSearchWP>"),
XmlRoot(Namespace="adSearch")]
public class adSearchWP : Microsoft.SharePoint.WebPartPages.WebPart,
Microsoft.SharePoint.WebPartPages.Communication.IR owProvider
{
public event RowProviderInitEventHandler RowProviderInit;
public event RowReadyEventHandler RowReady;

private bool isConnected = false;
private bool submitClicked = false;

private string[] myFieldNames;
private string[] myFieldDisplayNames;

private DataGrid myDataGrid;

// Create Web Part user interface controls.
protected TextBox searchBox;
protected Button searchButton;

public override void EnsureInterfaces()
{
Debug.Write("Ensuring interfaces.");
RegisterInterface("MGRowProvider", //InterfaceName
InterfaceTypes.IRowProvider, //InterfaceType
WebPart.UnlimitedConnections, //MaxConnections
ConnectionRunAt.Server, //RunAtOptions
this, //InterfaceObject
"",
//InterfaceClientReference
"Provide Data To...", //MenuLabel
"Provides a row of data to a consumer Web Part.", //Description
true);
//allowCrossPageConnection
}

public override ConnectionRunAt CanRunAt()
{
return ConnectionRunAt.Server;
}

public override void PartCommunicationConnect(
string interfaceName,
WebPart connectedPart,
string connectedInterfaceName,
ConnectionRunAt runAt)
{
if (interfaceName == "MGRowProvider")
{
Debug.Write("Connected.");
isConnected = true;
EnsureChildControls();
}
}

public override void PartCommunicationInit()
{
if( isConnected)
{
if (RowProviderInit != null)
{
RowProviderInitEventArgs rowProviderInitArgs = new
RowProviderInitEventArgs();
rowProviderInitArgs.FieldList = myFieldNames;
rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
RowProviderInit(this,rowProviderInitArgs);
}
}
else
Debug.Write("Need to send something...init");
}

public override void PartCommunicationMain()
{
if (isConnected)
{
if (RowReady != null)
{
RowReadyEventArgs rowReadyArgs = new RowReadyEventArgs();

if (submitClicked)
{
DataRow[] dr = new DataRow[1];
dr[0] = ((DataTable)myDataGrid.DataSource).Rows[0];
rowReadyArgs.Rows = dr;
rowReadyArgs.SelectionStatus = "Standard";
}
RowReady(this,rowReadyArgs);
}
}
else
Debug.Write("Need to send something...main");
}

public override InitEventArgs GetInitEventArgs(string interfaceName)
{
if (interfaceName == "MGRowProvider")
{
EnsureChildControls();
RowProviderInitEventArgs rowProviderInitArgs = new
RowProviderInitEventArgs();
rowProviderInitArgs.FieldList = myFieldNames;
rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
return(rowProviderInitArgs);
}
else
return(null);
}

/// <summary>
/// Render this Web Part to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void RenderWebPart(HtmlTextWriter output)
{
EnsureChildControls();
Debug.Write("rendering web part.");
output.RenderBeginTag("div");

// Check if connected.
if(isConnected)
{
Debug.Write("Connected. Rendering web part");
// Line break.
output.RenderBeginTag(HtmlTextWriterTag.Br);
output.RenderEndTag();

output.RenderBeginTag(HtmlTextWriterTag.Table);
output.RenderBeginTag(HtmlTextWriterTag.Tr);
output.RenderBeginTag(HtmlTextWriterTag.Th);
output.Write("Search For:");
output.RenderEndTag();
output.RenderBeginTag("td");
searchBox.RenderControl(output);
output.RenderEndTag();
output.RenderBeginTag("td");
searchButton.RenderControl(output);
output.RenderEndTag();
output.RenderEndTag();
output.RenderEndTag();

}
else
{
Debug.Write("Not connected, writing message.");
// The Web Part isn't connected.
output.Write("Not connected.");
}
output.RenderEndTag();
}
protected override void CreateChildControls()
{
Debug.Write("Creating child controls");
try
{
Debug.Write("Setting ID.");
searchBox.ID = "srchBox";
Debug.Write("Done setting ID. Setting width.");
this.searchBox.Width=Unit.Percentage(100);
Debug.Write("Done setting width. Adding search box.");
this.Controls.Add(searchBox);
Debug.Write("Created Search Box");
}
catch (Exception ex)
{
Debug.Write("Exception - search box: " + ex);
}

try
{
this.searchButton.Text = "Submit";
this.searchButton.Click += new System.EventHandler(searchButton_Click);
this.Controls.Add(searchButton);
Debug.Write("Created Search Button");
}
catch (Exception ex)
{
Debug.Write("Exception - search button: " + ex);
}

}

private void searchButton_Click(object sender, EventArgs e)
{
submitClicked = true; //user clicked button, set to true
Debug.Write("Button clicked.");
DataTable dataTable = new DataTable();
// Add three column objects to the table.
DataColumn anrColumn = new DataColumn();
anrColumn.DataType = System.Type.GetType("System.String");
anrColumn.ColumnName = "anr";
anrColumn.Caption = "ANR";
dataTable.Columns.Add(anrColumn);
DataRow dataRow;
dataRow = dataTable.NewRow();
// Then add the new row to the collection.
dataRow["anr"] = searchBox.Text;
dataTable.Rows.Add(dataRow);

myDataGrid.DataSource = dataTable;
myDataGrid.ID = "DataGrid";
myDataGrid.Attributes.Add("WDFLibID", "ServerSideRowProvider_DataGrid");
myDataGrid.DataBind();

//Set the DataTable FieldName information.
//This information will be passed to the Consumer by
//firing the RowProviderInit event.
int columnCount = dataTable.Columns.Count;
myFieldNames = new string[columnCount];
myFieldDisplayNames = new string[columnCount];

for(int i = 0; i < columnCount; i++)
{
myFieldNames[i] = dataTable.Columns[i].ColumnName;
myFieldDisplayNames[i] = dataTable.Columns[i].Caption;
}
}

}
}System.NullReferenceException iundicates that you are, in your code
somewhere, referencing an object that doesn't exist. For example:

object o;

string s = o.ToString(); // As o is not initialized to anything, you will
get a System.NullReferenceException

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Neither a follower
nor a lender be.

"Joe" <Joe@.discussions.microsoft.com> wrote in message
news:F9BD4158-B270-44D2-8572-379F055F4F4C@.microsoft.com...
> I am new to .NET and C#. I am deploying the SPS web part that appears
below
> and I am getting System.NullReferenceException in my CreateChildControls
> method. The last item shown by my debugger prior to the exception is
> "Setting ID."
> Any assistance would be greatly appreciated.
> Joe Mack
> -----
> CODE
> -----
> using System;
> using System.ComponentModel;
> using System.Web.UI;
> using System.Web.UI.WebControls;
> using System.Xml.Serialization;
> using System.Runtime.InteropServices;
> using System.Diagnostics;
> using Microsoft.SharePoint;
> using Microsoft.SharePoint.Utilities;
> using Microsoft.SharePoint.WebPartPages;
> using Microsoft.SharePoint.WebPartPages.Communication;
> using System.Data;
> namespace adSearch
> {
> /// <summary>
> /// Description for WebPart1.
> /// </summary>
> [DefaultProperty("Text"),
> ToolboxData("<{0}:adSearchWP runat=server></{0}:adSearchWP>"),
> XmlRoot(Namespace="adSearch")]
> public class adSearchWP : Microsoft.SharePoint.WebPartPages.WebPart,
> Microsoft.SharePoint.WebPartPages.Communication.IR owProvider
> {
> public event RowProviderInitEventHandler RowProviderInit;
> public event RowReadyEventHandler RowReady;
> private bool isConnected = false;
> private bool submitClicked = false;
> private string[] myFieldNames;
> private string[] myFieldDisplayNames;
> private DataGrid myDataGrid;
>
> // Create Web Part user interface controls.
> protected TextBox searchBox;
> protected Button searchButton;
> public override void EnsureInterfaces()
> {
> Debug.Write("Ensuring interfaces.");
> RegisterInterface("MGRowProvider", //InterfaceName
> InterfaceTypes.IRowProvider, //InterfaceType
> WebPart.UnlimitedConnections, //MaxConnections
> ConnectionRunAt.Server, //RunAtOptions
> this, //InterfaceObject
> "",
> //InterfaceClientReference
> "Provide Data To...", //MenuLabel
> "Provides a row of data to a consumer Web Part.", //Description
> true);
> //allowCrossPageConnection
> }
> public override ConnectionRunAt CanRunAt()
> {
> return ConnectionRunAt.Server;
> }
> public override void PartCommunicationConnect(
> string interfaceName,
> WebPart connectedPart,
> string connectedInterfaceName,
> ConnectionRunAt runAt)
> {
> if (interfaceName == "MGRowProvider")
> {
> Debug.Write("Connected.");
> isConnected = true;
> EnsureChildControls();
> }
> }
> public override void PartCommunicationInit()
> {
> if( isConnected)
> {
> if (RowProviderInit != null)
> {
> RowProviderInitEventArgs rowProviderInitArgs = new
> RowProviderInitEventArgs();
> rowProviderInitArgs.FieldList = myFieldNames;
> rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
> RowProviderInit(this,rowProviderInitArgs);
> }
> }
> else
> Debug.Write("Need to send something...init");
> }
> public override void PartCommunicationMain()
> {
> if (isConnected)
> {
> if (RowReady != null)
> {
> RowReadyEventArgs rowReadyArgs = new RowReadyEventArgs();
> if (submitClicked)
> {
> DataRow[] dr = new DataRow[1];
> dr[0] = ((DataTable)myDataGrid.DataSource).Rows[0];
> rowReadyArgs.Rows = dr;
> rowReadyArgs.SelectionStatus = "Standard";
> }
> RowReady(this,rowReadyArgs);
> }
> }
> else
> Debug.Write("Need to send something...main");
> }
> public override InitEventArgs GetInitEventArgs(string interfaceName)
> {
> if (interfaceName == "MGRowProvider")
> {
> EnsureChildControls();
> RowProviderInitEventArgs rowProviderInitArgs = new
> RowProviderInitEventArgs();
> rowProviderInitArgs.FieldList = myFieldNames;
> rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
> return(rowProviderInitArgs);
> }
> else
> return(null);
> }
> /// <summary>
> /// Render this Web Part to the output parameter specified.
> /// </summary>
> /// <param name="output"> The HTML writer to write out to </param>
> protected override void RenderWebPart(HtmlTextWriter output)
> {
> EnsureChildControls();
> Debug.Write("rendering web part.");
> output.RenderBeginTag("div");
> // Check if connected.
> if(isConnected)
> {
> Debug.Write("Connected. Rendering web part");
> // Line break.
> output.RenderBeginTag(HtmlTextWriterTag.Br);
> output.RenderEndTag();
> output.RenderBeginTag(HtmlTextWriterTag.Table);
> output.RenderBeginTag(HtmlTextWriterTag.Tr);
> output.RenderBeginTag(HtmlTextWriterTag.Th);
> output.Write("Search For:");
> output.RenderEndTag();
> output.RenderBeginTag("td");
> searchBox.RenderControl(output);
> output.RenderEndTag();
> output.RenderBeginTag("td");
> searchButton.RenderControl(output);
> output.RenderEndTag();
> output.RenderEndTag();
> output.RenderEndTag();
> }
> else
> {
> Debug.Write("Not connected, writing message.");
> // The Web Part isn't connected.
> output.Write("Not connected.");
> }
> output.RenderEndTag();
> }
> protected override void CreateChildControls()
> {
> Debug.Write("Creating child controls");
> try
> {
> Debug.Write("Setting ID.");
> searchBox.ID = "srchBox";
> Debug.Write("Done setting ID. Setting width.");
> this.searchBox.Width=Unit.Percentage(100);
> Debug.Write("Done setting width. Adding search box.");
> this.Controls.Add(searchBox);
> Debug.Write("Created Search Box");
> }
> catch (Exception ex)
> {
> Debug.Write("Exception - search box: " + ex);
> }
> try
> {
> this.searchButton.Text = "Submit";
> this.searchButton.Click += new System.EventHandler(searchButton_Click);
> this.Controls.Add(searchButton);
> Debug.Write("Created Search Button");
> }
> catch (Exception ex)
> {
> Debug.Write("Exception - search button: " + ex);
> }
> }
> private void searchButton_Click(object sender, EventArgs e)
> {
> submitClicked = true; //user clicked button, set to true
> Debug.Write("Button clicked.");
> DataTable dataTable = new DataTable();
> // Add three column objects to the table.
> DataColumn anrColumn = new DataColumn();
> anrColumn.DataType = System.Type.GetType("System.String");
> anrColumn.ColumnName = "anr";
> anrColumn.Caption = "ANR";
> dataTable.Columns.Add(anrColumn);
> DataRow dataRow;
> dataRow = dataTable.NewRow();
> // Then add the new row to the collection.
> dataRow["anr"] = searchBox.Text;
> dataTable.Rows.Add(dataRow);
> myDataGrid.DataSource = dataTable;
> myDataGrid.ID = "DataGrid";
> myDataGrid.Attributes.Add("WDFLibID", "ServerSideRowProvider_DataGrid");
> myDataGrid.DataBind();
> //Set the DataTable FieldName information.
> //This information will be passed to the Consumer by
> //firing the RowProviderInit event.
> int columnCount = dataTable.Columns.Count;
> myFieldNames = new string[columnCount];
> myFieldDisplayNames = new string[columnCount];
> for(int i = 0; i < columnCount; i++)
> {
> myFieldNames[i] = dataTable.Columns[i].ColumnName;
> myFieldDisplayNames[i] = dataTable.Columns[i].Caption;
> }
> }
> }
> }
Kevin:

Thanks.

I was failing to instantiate my objects in the CreateChildControls method.
All I did was add two lines: "searchBox = new TextBox();" and
"searchButton = new Button();"

Joe

"Kevin Spencer" wrote:

> System.NullReferenceException iundicates that you are, in your code
> somewhere, referencing an object that doesn't exist. For example:
> object o;
> string s = o.ToString(); // As o is not initialized to anything, you will
> get a System.NullReferenceException
> --
> HTH,
> Kevin Spencer
> ..Net Developer
> Microsoft MVP
> Neither a follower
> nor a lender be.
> "Joe" <Joe@.discussions.microsoft.com> wrote in message
> news:F9BD4158-B270-44D2-8572-379F055F4F4C@.microsoft.com...
> > I am new to .NET and C#. I am deploying the SPS web part that appears
> below
> > and I am getting System.NullReferenceException in my CreateChildControls
> > method. The last item shown by my debugger prior to the exception is
> > "Setting ID."
> > Any assistance would be greatly appreciated.
> > Joe Mack
> > -----
> > CODE
> > -----
> > using System;
> > using System.ComponentModel;
> > using System.Web.UI;
> > using System.Web.UI.WebControls;
> > using System.Xml.Serialization;
> > using System.Runtime.InteropServices;
> > using System.Diagnostics;
> > using Microsoft.SharePoint;
> > using Microsoft.SharePoint.Utilities;
> > using Microsoft.SharePoint.WebPartPages;
> > using Microsoft.SharePoint.WebPartPages.Communication;
> > using System.Data;
> > namespace adSearch
> > {
> > /// <summary>
> > /// Description for WebPart1.
> > /// </summary>
> > [DefaultProperty("Text"),
> > ToolboxData("<{0}:adSearchWP runat=server></{0}:adSearchWP>"),
> > XmlRoot(Namespace="adSearch")]
> > public class adSearchWP : Microsoft.SharePoint.WebPartPages.WebPart,
> > Microsoft.SharePoint.WebPartPages.Communication.IR owProvider
> > {
> > public event RowProviderInitEventHandler RowProviderInit;
> > public event RowReadyEventHandler RowReady;
> > private bool isConnected = false;
> > private bool submitClicked = false;
> > private string[] myFieldNames;
> > private string[] myFieldDisplayNames;
> > private DataGrid myDataGrid;
> > // Create Web Part user interface controls.
> > protected TextBox searchBox;
> > protected Button searchButton;
> > public override void EnsureInterfaces()
> > {
> > Debug.Write("Ensuring interfaces.");
> > RegisterInterface("MGRowProvider", //InterfaceName
> > InterfaceTypes.IRowProvider, //InterfaceType
> > WebPart.UnlimitedConnections, //MaxConnections
> > ConnectionRunAt.Server, //RunAtOptions
> > this, //InterfaceObject
> > "",
> > //InterfaceClientReference
> > "Provide Data To...", //MenuLabel
> > "Provides a row of data to a consumer Web Part.", //Description
> > true);
> > //allowCrossPageConnection
> > }
> > public override ConnectionRunAt CanRunAt()
> > {
> > return ConnectionRunAt.Server;
> > }
> > public override void PartCommunicationConnect(
> > string interfaceName,
> > WebPart connectedPart,
> > string connectedInterfaceName,
> > ConnectionRunAt runAt)
> > {
> > if (interfaceName == "MGRowProvider")
> > {
> > Debug.Write("Connected.");
> > isConnected = true;
> > EnsureChildControls();
> > }
> > }
> > public override void PartCommunicationInit()
> > {
> > if( isConnected)
> > {
> > if (RowProviderInit != null)
> > {
> > RowProviderInitEventArgs rowProviderInitArgs = new
> > RowProviderInitEventArgs();
> > rowProviderInitArgs.FieldList = myFieldNames;
> > rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
> > RowProviderInit(this,rowProviderInitArgs);
> > }
> > }
> > else
> > Debug.Write("Need to send something...init");
> > }
> > public override void PartCommunicationMain()
> > {
> > if (isConnected)
> > {
> > if (RowReady != null)
> > {
> > RowReadyEventArgs rowReadyArgs = new RowReadyEventArgs();
> > if (submitClicked)
> > {
> > DataRow[] dr = new DataRow[1];
> > dr[0] = ((DataTable)myDataGrid.DataSource).Rows[0];
> > rowReadyArgs.Rows = dr;
> > rowReadyArgs.SelectionStatus = "Standard";
> > }
> > RowReady(this,rowReadyArgs);
> > }
> > }
> > else
> > Debug.Write("Need to send something...main");
> > }
> > public override InitEventArgs GetInitEventArgs(string interfaceName)
> > {
> > if (interfaceName == "MGRowProvider")
> > {
> > EnsureChildControls();
> > RowProviderInitEventArgs rowProviderInitArgs = new
> > RowProviderInitEventArgs();
> > rowProviderInitArgs.FieldList = myFieldNames;
> > rowProviderInitArgs.FieldDisplayList = myFieldDisplayNames;
> > return(rowProviderInitArgs);
> > }
> > else
> > return(null);
> > }
> > /// <summary>
> > /// Render this Web Part to the output parameter specified.
> > /// </summary>
> > /// <param name="output"> The HTML writer to write out to </param>
> > protected override void RenderWebPart(HtmlTextWriter output)
> > {
> > EnsureChildControls();
> > Debug.Write("rendering web part.");
> > output.RenderBeginTag("div");
> > // Check if connected.
> > if(isConnected)
> > {
> > Debug.Write("Connected. Rendering web part");
> > // Line break.
> > output.RenderBeginTag(HtmlTextWriterTag.Br);
> > output.RenderEndTag();
> > output.RenderBeginTag(HtmlTextWriterTag.Table);
> > output.RenderBeginTag(HtmlTextWriterTag.Tr);
> > output.RenderBeginTag(HtmlTextWriterTag.Th);
> > output.Write("Search For:");
> > output.RenderEndTag();
> > output.RenderBeginTag("td");
> > searchBox.RenderControl(output);
> > output.RenderEndTag();
> > output.RenderBeginTag("td");
> > searchButton.RenderControl(output);
> > output.RenderEndTag();
> > output.RenderEndTag();
> > output.RenderEndTag();
> > }
> > else
> > {
> > Debug.Write("Not connected, writing message.");
> > // The Web Part isn't connected.
> > output.Write("Not connected.");
> > }
> > output.RenderEndTag();
> > }
> > protected override void CreateChildControls()
> > {
> > Debug.Write("Creating child controls");
> > try
> > {
> > Debug.Write("Setting ID.");
> > searchBox.ID = "srchBox";
> > Debug.Write("Done setting ID. Setting width.");
> > this.searchBox.Width=Unit.Percentage(100);
> > Debug.Write("Done setting width. Adding search box.");
> > this.Controls.Add(searchBox);
> > Debug.Write("Created Search Box");
> > }
> > catch (Exception ex)
> > {
> > Debug.Write("Exception - search box: " + ex);
> > }
> > try
> > {
> > this.searchButton.Text = "Submit";
> > this.searchButton.Click += new System.EventHandler(searchButton_Click);
> > this.Controls.Add(searchButton);
> > Debug.Write("Created Search Button");
> > }
> > catch (Exception ex)
> > {
> > Debug.Write("Exception - search button: " + ex);
> > }
> > }
> > private void searchButton_Click(object sender, EventArgs e)
> > {
> > submitClicked = true; //user clicked button, set to true
> > Debug.Write("Button clicked.");
> > DataTable dataTable = new DataTable();
> > // Add three column objects to the table.
> > DataColumn anrColumn = new DataColumn();
> > anrColumn.DataType = System.Type.GetType("System.String");
> > anrColumn.ColumnName = "anr";
> > anrColumn.Caption = "ANR";
> > dataTable.Columns.Add(anrColumn);
> > DataRow dataRow;
> > dataRow = dataTable.NewRow();
> > // Then add the new row to the collection.
> > dataRow["anr"] = searchBox.Text;
> > dataTable.Rows.Add(dataRow);
> > myDataGrid.DataSource = dataTable;
> > myDataGrid.ID = "DataGrid";
> > myDataGrid.Attributes.Add("WDFLibID", "ServerSideRowProvider_DataGrid");
> > myDataGrid.DataBind();
> > //Set the DataTable FieldName information.
> > //This information will be passed to the Consumer by
> > //firing the RowProviderInit event.
> > int columnCount = dataTable.Columns.Count;
> > myFieldNames = new string[columnCount];
> > myFieldDisplayNames = new string[columnCount];
> > for(int i = 0; i < columnCount; i++)
> > {
> > myFieldNames[i] = dataTable.Columns[i].ColumnName;
> > myFieldDisplayNames[i] = dataTable.Columns[i].Caption;
> > }
> > }
> > }
> > }
>
On Tue, 9 Nov 2004 10:53:03 -0800, Joe <Joe@.discussions.microsoft.com>
wrote:

>I am new to .NET and C#. I am deploying the SPS web part that appears below
>and I am getting System.NullReferenceException in my CreateChildControls
>method. The last item shown by my debugger prior to the exception is
>"Setting ID."
>Any assistance would be greatly appreciated.
>Joe Mack
> <SNIP CODE
You are not instantiating search Box before assigning the .ID in this
line:
searchBox.ID = "srchBox";

You need to instantiate the control like so:
searchBox = new TextBox();

This also goes for any other controls you use as well.

--
Thanks,
Chris Simmons
newsgroup.replies@.netchris.com

0 comments:

Post a Comment