.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

FindControl returns null

Posted By:      Posted Date: September 13, 2010    Points: 0   Category :ASP.Net
I am trying to fetch two Labels within a Repeater element to attach data to; which Label is assigned which Data Field depends on the result of a Radio Button List, hence why I need to fetch them in the code behind. This is the ASP.NET code: <asp:View ID="vwSportType" runat="server"> <table> <tr> <td rowspan="2"> <span class="boldtext">Select type of sport:</span><br /><br /> <asp:ListBox ID="lbType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbType_OnSelectedIndexChanged" Height="300px" Width="12em"> </asp:ListBox> </td> <td width="70%"> <span class="boldtext">Show by: <asp:RadioButtonList ID="rbSportType" runat="server" RepeatDirection="Horizontal"> <asp:ListItem Text="Date, Sport" Selected="True" Value="0"></asp:ListItem> <asp:ListItem Text="Sport,

View Complete Post

More Related Resource Links

Why it returns null (GridView)TemplateContainer.FindControl("gridView")?



I created a new custom field definition.

But on CreateChildControls event it always return null in my components. Where is error? What should I do to make work it properly?


protected override void CreateChildControls()


if (this.Field == null) return;


if (this.Field != null && this.ControlMode!= SPControlMode.Display)

this.MyPrefix = (Label)TemplateContainer.FindControl("MyPrefix");
if (this.MyPrefix == null)
    throw new ArgumentException("Corrupted PermissionControl template - missing ProofHQUserPermissionPrefix.");
this.gridView = (GridView)TemplateContainer.FindControl("gridView");
if (this.gridView == null)
    throw new ArgumentException("Corrupted PermissionControl template - missing GridView.");



All components are defined in template PermissionControl.

Page.FindControl Causing Null Reference Exception


Hi guys,

I developed a page in VWD 2008 and it works perfectly locally, but when I deployed it on the server every Page.FindControl() call is causing the NullReference Exception "Object reference not set to an instance of an object. " Can anyone help me out? Code is below


Mike Marshall

            For i As Integer = 1 To 10
                If (CType(Page.FindControl("last_" & i), TextBox).Text.Length > 0) Or (CType(Page.FindControl("first_" & i), TextBox).Text.Length > 0) Or (CType(Page.FindControl("dob_" & i), TextBox).Text.Length > 0) Then
                    Dim person_entry(7) As String
                    person_entry(0) = info_list.Count - 1
                    person_entry(1) = CType(Page.FindControl("last_" & i), TextBox).Text
                    person_entry(2) = CType(Page.FindControl("first_" & i), TextBox).Text
                    person_entry(3) = CType(Page.FindControl("dob_" & i), TextBox).Text
                    person_entry(4) = CType(Page.FindControl("appear_" & i), TextBox).Text
                    person_entry(5) = CType(Page.FindControl("mental_" & i), TextBox).Text
                    person_entry(6) = CType(Page.FindControl("behave_" & i), TextB

Linq to SQL returns null for DateTime fields.


I have a linq to sql entity class in which I declared some DateTime fileds like this:

[Column(DbType = "smalldatetime")]
public DateTime? StartDate { get; set; }

And this is how I fetch data form repository:

return repository.Logs.OrderByDescending(l => l.LogID).FirstOrDefault();

All non DateTime fields are filled properly but all datetimes are null.

[Column(DbType = "smalldatetime")]

        public DateTime? StartDate { get; set; }

BuildManager.GetType returns null until application pool recycles

Our application uses the Enterprise Library's PropertyProxyValidator class to validate user input (v4.1 - Oct 2008).  On occassion, the code will raise an exception saying the source type cannot be found.  This error persists until the application pools recycle at night, at which point everything works again.  It tends to only affect one of the web front ends at a time (there are two). I tracked down where the exception was being raised, and this is the section of code:Type IValidationIntegrationProxy.ValidatedType { get { if (string.IsNullOrEmpty(this.sourceTypeName)) { throw new InvalidOperationException(Resources.ExceptionNullSourceTypeName); } Type validatedType = BuildManager.GetType(this.SourceTypeName, false, false); if (validatedType == null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentUICulture, Resources.ExceptionInvalidSourceTypeName, this.sourceTypeName)); } return validatedType; } } (As you can see, the value for this.SourceTypeName is shown in the exception and I've checked that it matches exactly.) We have never been able to reproduce this exception and at this point don't have any ideas left as far as causes.  For a while, my suspicion was that it was related to the Temporary ASP.NET Files folder.  The last

Nested controls in UserControl return null (FindControl)

Hi everyone, I have a very weird issue. I have a UserControl that has some controls inside. I want to refer those controls after, in another postback. But when I try to get them the ".Controls" property of my controls returns null. I'm working on vs2008 Here is the sample code: public partial class MyUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { foreach (Control control in this.Controls) { Response.Write(control.ClientID); } } private void MyTable() { Table table = new Table(); TableRow row = new TableRow(); TableCell cell = new TableCell(); CheckBox check = new CheckBox(); check.ID = "theId"; check.Text = "My Check"; check.AutoPostBack = true; cell.Controls.Add(check); row.Cells.Add(cell); check = new CheckBox(); check.ID = "theOther"; check.AutoPostBack = true; check.Text = "My Other Check"; cell = new TableCell(); cell.Controls.Add(check); row.Cells.Add(cell); table.Rows.Add(row); this.Controls.Add(table); } protected override void Render(HtmlTextWriter writer) { MyTable(); base.Render(writer); } } And in the Default.aspx is like:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.cs" Inherits="Tester.Default" %> &

Registry OpenSubKey returns null

Hi,It seemed to be the right place to post to.My problem is that when I try to read registry key, I get null value, even if it exists (regedit shows it exists).Application is windows service with Log On As Local System and registry key im trying to read is in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSIDOn my development machine (x64 win7) it works fine. But in live server (x64 windows server 2008 r2) I get NULL. These operating systems should have similar policies or does Local System on server 2008 have any restrictions i should know about?RegardsMax

Why this returns null

hi friends, i have a table AppUser.UsersUserRole that has the following structure: idx auto ur_id int -- user role id id int    -- user id that has the following data:  From Drop Box  when i ran query to returns a csv: declare @csv nvarchar(max) select @csv = @csv + coalesce( convert(nvarchar(max), ur_id) + ',','' ) from AppUser.UsersUserRoles where id = 28 select @csv it returns:  From Drop Box  but there are three records for 28, why it displays null, how do i fix this? thanks

SCOPE_IDENTITY() returns null after paramerized INSERT


I have a very simple database, without any triggers at this point. One of my tbales has a auto increment key (IDENTITY field). As the record has a string attribute, which valeu is received from the user, I insert a new records with a parametized INSERT statement. After insertion I try to fetch the new record's ID with the sttament SELECT SCOPE_IDENTITY(), but ti return null - while SELECT @IDENTITY and SELECT IDENT_CURRENT returns the valid values.

Moreover, if - for testing purposes - I execute the same insert without parameters, (i.e. providing the string value directly in the INSERT statement), then even SCOPE_IDENTITY() returns the correct value.

I didn't find any reference in the documentation regarding such restriction. Is is a known bug or the result of some misunderstading?

Findcontrol returns an empty control


Hello all,

The concept of findcontrol seems to elude me somewhat and I would like some advice if anyone can spare it.

My SP page layout contains a richhtmlfield with a highly descriptive ID of "RichHtmlField1". The same page layout contains a custom user control that needs to read te contents of this richhtmlfield and e-mail it.

To get the content I figured I'd use the findcontrol function. And this works fine. I then cast the control to a richhtmlfield and try to access the .Html property. But apparently that's empty. I don't understand that, since if you look at the page the content of the field is clearly filled.

Can anybody shed some light on the subject?

My (highly professional) code:

HtmlGenericControl myDiv = new HtmlGenericControl("div");

Control cntlTest = this.Parent.FindControl("RichHtmlField1");

//This works and gives me the proper results
myDiv.InnerHtml += cntlTest.ID + " || " + cntlTest.GetType();

//This is empty
myDiv.InnerHtml += 

Downloading a document from a sharepoint site to local file system, copy web service returns null

Hi Guys,
               I am trying to get this done for the last 2 days and I am still banging my head to the wall.
All I need to do is to download files from my sharepoint site library that uses integrated windows authentication. I was using copy webservice : getItem method to accomplish this.

CopyService.GetItem(copySource, out myFieldInfoArray, out myByteArray);

Problem : myByteArray is always returned as NULL

Note: I have tried the same with another site that uses forms authentication but the result was the same (NULL !!)

This is my code:


Copy copy = new CopyService.Copy();


Session returns null


on page load im Assigning a table to session["Tb"]

on changing dropdown i hv to change gridview but thr session["Tb"] returns null...

Could anyone help me to solve tis 


Control.FromHandle returns null


I've a process: "Example.exe" (process A), which contains a main form. I launch a second instance of the process with some parameters: "Example.exe -param1 -param2" (process B). In the second instance i check for the parameters by using the args array of the Main() function and if there are any, I'd like to copy parameters from the main form of the first instance of the process to a main form of the new second instance of the process. To achieve that in the second instance I retrieve the processA.MainWindowHandle and I try to do sometihing like:

Form mainFormProcessB  = Control.FromHandle(processA.MainWindowHandle) as Form

This doesn't work because Control.FromHandle(processA.MainWindowHandle) return null.

I don't underdstand why processA.MainWindowHandle had a value equal to 509062 and when i checked for the handle value (using Spy++) I obtained the exadecimal: 7C486, which is 509062. why does Control.FromHandle(processA.MainWindowHandle) fails returning null?




Andrea Scarmagnani

GetUserProfileByName method in userprofileservice.asmx returns null values when used in Service Refe


I'm using Silverlight 4 to call GetUserProfileByName method of the SharePoint 2007 userprofileservice.asmx web service. For each of the PropertyData in the e.Result object that is returned, the Values array is null.

Below is the Completed event handler. Execution gets inside the if block for each of the PropertyData.


void client_GetUserProfileByNameCompleted(object sender, GetUserProfileByNameCompletedEventArgs e)
 foreach (PropertyData prop in e.Result)
  if (prop.Values == null) // this is ALWAYS true for each prop


After some investigation, I've found out this only happens when userprofileservice.asmx is added as a Service Reference. I tested this out by creating an ASP.NET project. In it I added userprofileservice.asmx as a Web Reference, and then as a Service Reference. For the Web Reference case,

RowCommand returns null value for controls which are not binded to Gridview source


I am tryting to reach controls in the gridview rows by RowCommand event. I can take values of controls which are binded to gridview source successfully . But for all other controls which is not binded to gridview returns NULL value. All controls run at server. Why is that?

Custom config returns NULL section despite "proper" definition


I have defined a custom config section but when I try to get the section, it's always null.

I can't see what I'm missing. The only thing that I can might be an issue is that the code is part of a library project ina a solution with a main project, so not sure if the app.config has to be under the main project instead.

Below is my code, any ideas?

    public class CustomConfiguration : ConfigurationSection
        [ConfigurationProperty("keys", IsRequired = false)]
        public KeyCollection Keys
                return this["keys"] as KeyCollection;

    public class Key : ConfigurationElement
        [ConfigurationProperty("name", IsRequired = false)]
        public string Name
                return this["name"] as string;

        [ConfigurationProperty("value", IsRequired = false)]
        public string Value
                return this["value"] as string;

    public class KeyCollection : ConfigurationElementCollection
        public Key this[int index]
                return base.Base

Type myType = a.GetType("Class1"); returns NULL

I created a class Class1 and generated a strong named assembly. Following is my simple class. But when i try to load this assembly using 
Assembly.Load() - > Type.GetType() returns null. Cannot figure out why? Below is the code for Assembly.Load
namespace LoadAssemblyTest
    public class Class1
        public void GetDriveInfo()
            Console.WriteLine("Drives: ");
            foreach (DriveInfo di in DriveInfo.GetDrives())
                Console.WriteLine(" {0} ({1}) ", di.Name, di.IsReady);

            Console.WriteLine("Press the drive letter to view the folder: ");
            ConsoleKeyInfo drive = Console.ReadKey(true);
            DirectoryInfo dir = new DirectoryInfo(drive.Key.ToString() + @":\");
            foreach (DirectoryInfo dirInfo in dir.GetDirectories())
                Console.WriteLine("\n " + dirInfo.FullName);

            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;



Convert XML to object returns null due to unwanted string


Hello All,

I am facing very odd problem, when I check my xml string than in header it contain one unwanted string square [], like below, due to that casting to object is not happening. Due to that it returns null

[]<?xml version="1.0"?>

But when I remove [] and convert to object then it works fine. Any one has any idea.

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend