Saturday, March 24, 2012

System.NullReferenceException

Hello people,

this is my first time ever to post a question on this asp.net forum, so I hope this would be a wonderful experience from here on.

Here is my problem, I get " System.NullReferenceException " this error at not a compile time, but atruntime time.

here is my code

protectedvoid dl_UpdateCommand(objectsource,DataListCommandEventArgs e)

{

// Read inthe ProductID from the DataKeys collection

intFileID =Convert.ToInt32(dl.DataKeys[e.Item.ItemIndex]);

// Readin the product name and price values

TextBoxtxtEditFileName = (TextBox)e.Item.FindControl("FileName");

TextBoxtxtEditDescription = (TextBox)e.Item.FindControl("Description");

stringFileNameValue =null;//"null" wil not work.Error Occurs here

if(txtEditFileName.Text.Trim().Length > 0)

FileNameValue =txtEditFileName.Text.Trim();

stringDescriptionValue =null;Error Occurs here

if(txtEditDescription.Text.Trim().Length > 0)

DescriptionValue =txtEditDescription.Text.Trim();

#region- "changed Updatemechanism"

// Call theUpdate method to Update FileName, Description...

SqlConnectionmyConnection =newSqlConnection(ConfigurationManager.ConnectionStrings["ARCCAOHelpConnectionString"].ConnectionString);

//stringsqlString = "SELECT * FROM ARCCA_FileUpload1 WHERE FileID=" + FileID;

stringsqlString ="SELECT * FROMARCCA_FileUpload1";

SqlDataAdapterdataAdapter =newSqlDataAdapter(sqlString,myConnection);

DataSetdataSet =newDataSet();

DataRowdataRow;

// Createcommand builder. This line automatically generates the update commands for you,so you don't

// have toprovide or create your own.

SqlCommandBuildersqlCmdBuild =newSqlCommandBuilder(dataAdapter);

// Set theMissingSchemaAction property to AddWithKey because Fill will not cause primary

// key &unique key information to be retrieved unless AddWithKey is specified.

dataAdapter.MissingSchemaAction =MissingSchemaAction.AddWithKey;

dataAdapter.Fill(dataSet,"ARCCA_FileUpload1");

dataRow = dataSet.Tables["ARCCA_FileUpload1"].NewRow();

dataRow["FileID"]=FileID;

dataRow["FileName"]=FileNameValue;

dataRow["Description"]=DescriptionValue;

dataSet.Tables["ARCCA_FileUpload1"].Rows.Add(dataRow);

// Revert theDataList back to its pre-editing state

dl.EditItemIndex = -1;

dl.DataBind();

}

now, how to fix it?

Set it to string.empty


SonuKapoor:

Set it to string.empty

i wonder why it shouldn't work ... setting a string to null works just fine with me ...


Trickass: You are right it should work with null as well.

eddieiam: Are you sure that this is line causing the error?


Hi Sonu,

the actual line thats causing the error isif (txtEditFileName.Text.Trim().Length > 0) . On this line, I get error: System.NullReferenceException: Object reference not set to an instance of an object


You have to make sure that the row contains a textbox with the id "FileName". Can you show me the HTML declaration of your GridView?



Anytime that you use FindControl, you should ALWAYS do a null check before using the control, as that is what you get if it doesn't find the control.

FindControl should always be used like this:
Control controlRef = e.Item.FindControl("FileName");
if ( controlRef != null )
{
TextBox txtEditFileName = (TextBox)controlRef;

// Remainder of processing for this TextBox...
}

Could be that "FileName" is not the correct ClientID for this control because of spelling, case-sensitivity, or that the control is inside of a container which changes the ClientID by adding on the container ClientID (masterPageID + "_" + controlID).

NC...


NC01: I have masterPage, but i am not assigning masterPageID to the control at the aspx page. Also, I've tried using the Control to FindControl it now gives me FileNameValue does not exist error


The easiest way to solve that is to bring the page up in your browser and do a View Source on it then find the control to see what the ending ClientID is.

NC...


Hold it! If this control is in a DataList, DataGrid, or GridView, etc, this should work, and could give you an idea of the problem.

protected void dl_UpdateCommand(object source, DataListCommandEventArgs e)
{
// Iterate through all controls on the row:
for (int i=0; i<e.Item.Controls.Count; i++)
{
Control controlRef = e.Item.Controls[i];
string controlId = string.Empty;

if ( controlRef is LinkButton )
controlId = ((LinkButton)controlRef).ClientID;
else if ( controlRef is Label )
controlId = ((Label)controlRef).ClientID;
else if ( controlRef is TextBox )
controlId = ((TextBox)controlRef).ClientID;
// else any other controls here
}
}

NC...


Hey uh, you good!. thanks for your effort in helping me. really do appriciate. but still i get the same error buddy. By the way, its a DataList that I am binding to. And

using the Edit template to edit. let me also post the aspx page for ref which will be down below after the cs code.

thanks.. again..

protected void dl_UpdateCommand(object source, DataListCommandEventArgs e)
{
//Iterate through all controls on the row:
// Iterate through all controls on the row:
for (int i = 0; i < e.Item.Controls.Count; i++)
{
Control controlRef = e.Item.Controls[i];
string controlId = string.Empty;

if (controlRef is LinkButton)
controlId = ((LinkButton)controlRef).ClientID;
else if (controlRef is Label)
controlId = ((Label)controlRef).ClientID;
else if (controlRef is TextBox)
controlId = ((TextBox)controlRef).ClientID;
// else any other controls here
}

// Read in the ProductID from the DataKeys collection
int FileID = Convert.ToInt32(dl.DataKeys[e.Item.ItemIndex]);

// Read in the product name and price values
TextBox txtEditFileName = (TextBox)e.Item.FindControl("FileName");
TextBox txtEditDescription = (TextBox)e.Item.FindControl("Description");
string FileNameValue = null; // "null" wil not work.
if (txtEditFileName.Text.Trim().Length > 0)
FileNameValue = txtEditFileName.Text.Trim();

string DescriptionValue = null;
if (txtEditDescription.Text.Trim().Length > 0)
DescriptionValue = txtEditDescription.Text.Trim();

#region- "changed Update mechanism"
// Call the Update method to Update FileName, Description...
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ARCCAOHelpConnectionString"].ConnectionString);
//string sqlString = "SELECT * FROM ARCCA_FileUpload1 WHERE FileID=" + FileID;
string sqlString = "SELECT * FROM ARCCA_FileUpload1";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlString,myConnection);
DataSet dataSet = new DataSet();
DataRow dataRow;

// Create command builder. This line automatically generates the update commands for you, so you don't
// have to provide or create your own.
SqlCommandBuilder sqlCmdBuild = new SqlCommandBuilder(dataAdapter);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

dataAdapter.Fill(dataSet,"ARCCA_FileUpload1");
dataRow = dataSet.Tables["ARCCA_FileUpload1"].NewRow();
dataRow["FileID"]=FileID;
dataRow["FileName"]= FileNameValue;
dataRow["Description"]= DescriptionValue;

dataSet.Tables["ARCCA_FileUpload1"].Rows.Add(dataRow);

// Revert the DataList back to its pre-editing state
dl.EditItemIndex = -1;
dl.DataBind();
#endregion

#region- "obselete Update mechanism"
//// Call the Update method to Update FileName, Description...
//using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ARCCAOHelpConnectionString"].ConnectionString))
//{
// myConnection.Open();
// string conString = "UPDATE ARCCA_FileUpload1 SET FileName ='txtEditFileName', Description ='txtEditDescription' WHERE FileID=" + FileID;
// using (SqlCommand cmd = new SqlCommand(conString, myConnection))
// {
// cmd.Connection.Open();
// SqlDataAdapter da = new SqlDataAdapter();
// da.UpdateCommand = cmd;
// DataSet dataSet = new DataSet();
// da.Fill(dataSet);
// }
//}

//// Revert the DataList back to its pre-editing state
//dl.EditItemIndex = -1;
//dl.DataBind();
#endregion
}

protected void dl_CancelCommand(object source, DataListCommandEventArgs e)
{
// Set the DataList's EditItemIndex property to -1
dl.EditItemIndex = -1;

// Rebind the data to the DataList
dl.DataBind();
}

<%@. Page Language="C#" MasterPageFile="~/ARCCAAccess.master" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" Title="Untitled Page" %
<%@. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:DataList runat="server" ID="dl" DataKeyField="FileID"
OnItemCommand="dl_ItemCommand"
OnEditCommand="dl_EditCommand" OnDeleteCommand="dl_DeleteCommand"
OnUpdateCommand="dl_UpdateCommand" OnCancelCommand="dl_CancelCommand" >

<ItemTemplate>
<cc1:HoverMenuExtender ID="HoverMenuExtender1" runat="server" TargetControlID="HypLnkFileName"
PopupControlID="Panel1" PopupPosition="Right" OffsetX="6" PopDelay="25" HoverCssClass="popupHover">
</cc1:HoverMenuExtender>
<asp:Panel ID="Panel1" runat="server" BackColor="White" BorderColor="Blue" BorderStyle="Solid"
BorderWidth="1px" CssClass="popupMenu" Width="350px" >
<asp:Label ID="lblDescription" ForeColor="black" Font-Size="14px"
runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>'></asp:Label>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="true" CommandName="Edit">Edit</asp:LinkButton>
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete">Delete</asp:LinkButton>
</asp:Panel>
<asp:LinkButton ID="HypLnkFileName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FileName") %>'></asp:LinkButton>
</ItemTemplate>

<EditItemTemplate>
<asp:Panel ID="Panel2" runat="server" BackColor="White" BorderColor="Blue" BorderStyle="Solid"
BorderWidth="1px" CssClass="popupMenu" Width="500px">
FileName :<asp:TextBox ID="txtEditFileName" Text='<%# DataBinder.Eval(Container.DataItem, "FileName") %>'
runat="server" ></asp:TextBox>
Description :<asp:TextBox ID="txtEditDescription" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>'
runat="server" Width="175px"></asp:TextBox>
<asp:LinkButton ID="btnUpdate" Text="Update" ForeColor="Red" CommandName="Update"
runat="server"></asp:LinkButton>
<asp:LinkButton ID="btnCancel" Text="Cancel" ForeColor="Red" CommandName="Cancel"
runat="server"></asp:LinkButton>
</asp:Panel>
</EditItemTemplate>

</asp:DataList>
</asp:Content


Try this:

Panel p = (Panel)e.Item.FindControl("Panel2");
TextBox txtEditDescription = (TextBox)p.FindControl("Description");


Try what SonuKapoor posted because txtEditFileName and txtEditDescription are definitely inside of the Panel2 container, so the ClientID would probably be dl_Panel2_txtEditFileName. So even the code that I gave you to test with wouldn't pick them up I don't think. It would only pickup HoverMenuExtender1, Panel1, HypLnkFileName, and Panel2 (I believe).

This should work for the FileName TextBox:
Panel p = (Panel)e.Item.FindControl("Panel2");
TextBox txtEditFileName = (TextBox)p.FindControl("txtEditFileName");

NC...


I don't think that you would need the ClientID anyways.


I was thinking if I need to place the contentPlaceHolder Id with FindControl to make it work. since I had a similar problem while adding export to excel some documents from web.

0 comments:

Post a Comment