.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

Control.FromHandle returns null

Posted By:      Posted Date: October 08, 2010    Points: 0   Category :Windows Application

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

View Complete Post

More Related Resource Links

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

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

Is there a method that returns the control's type, such as "TextBox", "TextBlock", "Canvas", etc.,

Hello, I have a method that is passed in a FrameworkElement Ctrl.  When I use Ctrl.GetType().ToString() I get "System.Window.Controls.TextBox" or another string if a different type of control is passed in.  All I am interested in is the text after the last dot/period.  In my searching I thought I came across something that just returned the portion I'm looking for, but now can't find it. Is there a method that returns the control's type, such as "TextBox", "TextBlock", "Canvas", etc., without its parents? Regards, Robert

FindControl returns null

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,

Tab Panel inside a User control - null referance to text box with set properties

Hi guys, Im having problems with the following: I have a user control which has a tabbed panel inside, I then have a public property which populates a textbox inside the tabbed panel, HOWEVER when I access the property on my ASPX page, it give me a null referance to textbox, I have tried using findControl but still finds nothing, Please help!! ASPX PAGE  <Registration:UserDetails UserID="23" ID="RegistrationUserDetails" runat="server" /> USER CONTROL<cc1:TabContainer ID="TabContainerRegistration" runat="server" ActiveTabIndex="1" > <cc1:TabPanel runat="server" ID="TabPanelAccessDetails" HeaderText="Access details"> <ContentTemplate> <table> <tr> <td>User ID</td> </tr> <tr> <td><asp:TextBox ID="UserIDTextBox" ReadOnly="true" runat="server" SkinID="InputBoxes"></asp:TextBox></td> </tr> </table> </ContentTemplate> </cc1:TabPanel> </cc1:TabContainer> CODE BEHINDprivate int _UserID; public int UserID { set { TextBox tb = (TextBox)TabContainerRegistration.

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 


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.

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') ;



Visual Web part with embedded User Control, fields are null


I have a legacy ASP.Net application that consisted of a series of ascx user controls which I am attempting to convert into visual web parts.  

I have wrapped each ascx in its own visual webpart and deployed to my site. Within my site I am able to add some of these to my pages and they render properly.

The ones that I am having difficulty with are those ascx user controls that have a child reference to other custom user controls.

For example I have CustomerinfoUserControl.ascx that has many fields within the control, but one is also a custom user control to select the date called DatePicker2UserControl.asx

Here is the declaration within CustomerInfoUserControl  and usage …



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