EzDevInfo.com

user-controls interview questions

Top user-controls frequently asked interview questions

Baseline snaplines in custom Winforms controls

I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.


Source: (StackOverflow)

Global Exception Handling for winforms control

When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?


Source: (StackOverflow)

Advertisements

InvalidCastException for Object of the same type - Custom Control Load

I have a very wired error, one of my custom controls seems that is create two compiled files, and when I try to load it dynamically with LoadControl() is just fail because can not cast the one to the other - even if they are exactly the same. I write the message to see that all is the same, is only change the compiled dll.

System.Web.HttpUnhandledException (0x80004005):     
 Exception of type 'System.Web.HttpUnhandledException' was thrown. --->             
    System.InvalidCastException:
[A]ASP.Modules_OneProduct_MedioumImage cannot be cast to
[B]ASP.Modules_OneProduct_MedioumImage.         

   Type A originates from 'App_Web_kg4bazz1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
in the context 'Default'
    at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\80ed7513\10eb08d9\App_Web_kg4bazz1.dll'.          

   Type B originates from 'App_Web_oneproduct_mediumimage.ascx.d1003923.4xoxco7b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 
in the context 'Default'    
    at location 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\80ed7513\10eb08d9\App_Web_oneproduct_mediumimage.ascx.d1003923.4xoxco7b.dll'.

The code

This is the code as it is right now after I have follow exactly what is written on MSDN:

foreach (int OneProductID in TheProductIdArrays)
{
    // here is the throw.
    ASP.Modules_OneProduct_MedioumImage OneProduct = 
        (ASP.Modules_OneProduct_MedioumImage)LoadControl(@"~/mod/OneProduct_MediumImage.ascx");

    // do some work with 
    //OneProduct
}

Previously I have Load the control without the ASP. but after this bug appears and looking for solution, I strictly follow what is on MSDN. The bug is still here no matter what I do.

I have also try both of this methods, each one alone, and together (again fail)

<%@ Register src="~/mod/OneProduct_MediumImage.ascx" tagname="OneProduct_MediumImage" tagprefix="uc1" %>
<%@ Reference Control="~/mod/OneProduct_MediumImage.ascx" %>

Config

My web.config, I have try with maxBatchSize 20, 100, 1000, also with optimizeCompilations true or false, but the bug is appears again.

<compilation debug="false" defaultLanguage="C#" batch="true"
maxBatchSize="800" batchTimeout="10800" optimizeCompilations="false"
targetFramework="4.0">

Now some details about

  • The error is random, in some compile appears, in some other not.
  • The project is a big one, the pages are live with a lot of people in every minute that ask to see something, but also appears when there is no one inside.
  • Is run on 64bit dot.net 4, Intergrated
  • Run as web garden but also tested and one pool alone (and get the same issue)
  • The session is off on the full project.
  • The pages are run from 2007 but this issue is appears the last month, unfortunately I can not find where and how is started, or what is trigger it because I late some days to see it.
  • Appears only one one custom control loads, the one that have heavy call.
  • I have change 4 times the code making small changes, or big changes and still there.
  • I have try with optimizeCompilations true and false and the same issue.
  • I have try also by stopping the web, delete all temporary files, reopening, and there was again.
  • I have try to place a mutex on global.asax when the application starts to lock only one compile at the time, but this fails also.
  • From the moment that works, then all is good, but if not works is not auto corrected.
  • The code that I load this custom control is exist and called in more than one places on the code, on different pages.
  • Other custom controls, with similar load did not have any problems.
  • ViewState is disabled for this custom control.
  • I have also try relocate some code, change the full function call with micro optimizes, no again fail.
  • Is work fine on development computer. I place batch="true" on web.config and the bug appears right away.
  • There are no other issues like that, like a bug that we can not fix no matter what. The system is run for days, the pool is NOT recycle at all, the memory is stable, and there is more free to use. The program is run for years now, but we change is almost every day with updates.
  • Under the same core code runs more than one sites (something like stackexchange) and all have the same random problem.
  • The AutoEventWireup is false
  • Its appears and on other custom control that I load the same way.

What I do now as workaround when this bug appears: I just force the project to recompile with a small change, and the error go away, until the next update.

I have a bug that try to solve the last tree weeks with out find the reason. I have try almost anything I can thing of, but all fails, and the bug appears again. So I post here maybe some can help me out and find a way out of this.

Last word: This bug is crazy, the custom control is the same, I do anything on it I only load it dynamically and boom, the compiler is have it two different times for some reason that only he knows - randomly.

Update 1

I been able to reproduce the bug on the developer machine. There I discover that the two dll modules that contains this custom control have a different.

The one was a bundle of 4 custom controls together. The other module was the custom control alone.

Workaround

After tree weeks trying to fix this bug I end up that this bug is appears when the compiler make batch compile of a directory, and bundle many different custom controls, in the same dll. So when I try to load it alone is throw this exception.

So I move the problematic custom control in a different directory alone and seems that I avoid it for now.

Update 2

Appears again, even after I move some files to a different directory. Is random and can not find a clear connection with what is triggers its.

Update 3

Because we have spot that the main issue here is the batch compile (batch="true") that compiles on the same dll many custom controls, one way to say to the compiler to NOT do that, is the maxBatchGeneratedFileSize parameter. I use it with a value of 100, and the issue appears again, now I have lower it to 40 and test it.

maxBatchGeneratedFileSize="40"

Source: (StackOverflow)

How to fix the flickering in User controls

In my application i am constantly moving from one control to another. I have created no. of user controls, but during navigation my controls gets flicker. it takes 1 or 2 sec to update. I tried to set this

SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
or
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
SetStyle(ControlStyles.DoubleBuffer, true);

but it didn't help... Each control has same background image with different controls. So what is the solution for it..
Thanks.


Source: (StackOverflow)

User Controls not showing up in the toolbox

I have some UserControls that I created in ProjectA. I have ProjectB that has a windows form that I want to put the controls on. Both of these projects are in a single solution. There's a reference to ProjectA from ProjectB so it can "see" the UserControls.

However, the UserControls do not show up in the toolbox for me to drag to the windows form.

I've tried rebuilding. I've also deleted the 'bin' directory to force a rebuild-all.

How do I get VS2008 to populate the toolbox with my UserControls?


Source: (StackOverflow)

How do I get the full url of the page I am on in C#

I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?


Source: (StackOverflow)

How to calculate the sum of the datatable column in asp.net?

I have a DataTable which has 5 columns:

  • ID
  • Name
  • Account Number
  • Branch
  • Amount

The DataTable contains 5 rows.

I want to show the sum of the Amount Column in a Label Control as "Total Amount"

What is the best way of doing this?


Source: (StackOverflow)

How do I add Dispose functionality to a C# UserControl?

I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:

  protected override void Dispose(bool disposing)
  {
     if (disposing && (components != null))
     {
        components.Dispose();
     }
     base.Dispose(disposing);
  }

If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.


Source: (StackOverflow)

What is the difference between a User Control Library and a Custom Control Library?

I am just coming up to speed on WPF and would like to create a reusable WPF control.

When I look at the options for creating projects in Visual Studio, I see "WPF User Control Library" and "WPF Custom Control Library". It's unclear to me what the difference is between them and my Google searches have not turned up any decent explanations.

I'd like to understand the differences between them and ideally see some examples of when to use one over the other.


Source: (StackOverflow)

User Control - Custom Properties

I have developed a User Control in Visual Studio (WinForms C#) and have a question.

I need the user of my User Control to be able to change certain string values and I would like them to be able to add the user control to their Form and click on it to bring up the Properties Pane where my User Control's custom properties will be displayed.

How can I have my own custom properties for my user control? For example:

My user control contains a TextBox, and I would like the user to be able to change the value of that TextBox via a property named "Text" or "Value" in the properties at Design-Time.


Source: (StackOverflow)

"The Controls collection cannot be modified because the control contains code blocks"

I am trying to create a simple user control that is a slider. When I add a AjaxToolkit SliderExtender to the user control I get this (*&$#()@# error:

    Server Error in '/' Application. The Controls collection cannot be modified because the control contains code blocks (i.e. ``). Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. ``).

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:

    [HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. ``).]    System.Web.UI.ControlCollection.Add(Control child) +8677431    AjaxControlToolkit.ScriptObjectBuilder.RegisterCssReferences(Control control) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ScriptObjectBuilder.cs:293 AjaxControlToolkit.ExtenderControlBase.OnLoad(EventArgs e) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ExtenderControlBase.cs:306 System.Web.UI.Control.LoadRecursive()
    +50    System.Web.UI.Control.LoadRecursive()
    +141    System.Web.UI.Control.LoadRecursive()
    +141    System.Web.UI.Control.LoadRecursive()
    +141    System.Web.UI.Control.LoadRecursive()             
    +141    System.Web.UI.Control.LoadRecursive()
    +141    System.Web.UI.Control.LoadRecursive()
    +141    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627


    Version Information: Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET Version:2.0.50727.3074

I have tried putting a placeholder in the user control and adding the textbox and slider extender to the placeholder programmatically and I still get the error.

Here is the simple code:

<table cellpadding="0" cellspacing="0" style="width:100%">
    <tbody>
        <tr>
            <td></td>
            <td>
                <asp:Label ID="lblMaxValue" runat="server" Text="Maximum" CssClass="float_right" />
                <asp:Label ID="lblMinValue" runat="server" Text="Minimum" />
            </td>
        </tr>
        <tr>
            <td style="width:60%;">
                <asp:CheckBox ID="chkOn" runat="server" /><asp:Label ID="lblPrefix" runat="server" />:&nbsp;<asp:Label ID="lblSliderValue" runat="server" />&nbsp;<asp:Label ID="lblSuffix" runat="server" />
            </td>
            <td style="text-align:right;width:40%;">                

                    <asp:TextBox ID="txtSlider" runat="server" Text="50" style="display:none;" />
                    <ajaxToolkit:SliderExtender ID="seSlider" runat="server" 
                        BehaviorID="seSlider" 
                        TargetControlID="txtSlider" 
                        BoundControlID="lblSliderValue" 
                        Orientation="Horizontal" 
                        EnableHandleAnimation="true" 
                        Length="200" 
                        Minimum="0" 
                        Maximum="100" 
                        Steps="1" />

            </td>
        </tr>
    </tbody>
</table>

What is the problem?


Source: (StackOverflow)

Disposing WPF User Controls

I have created a custom WPF user control which is intended to be used by a third party. My control has a private member which is disposable, and I would like to ensure that its dispose method will always get called once the containing window/application is closed. However, UserControl is not disposable. I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. If at all possible, I don't want to rely on consumers of my control remembering to call a specific Dispose method.

 public partial class MyWpfControl : UserControl
 {
     SomeDisposableObject x;

     // where does this code go?
     void Somewhere() 
     {
         if (x != null)
         {
             x.Dispose();
             x = null;
         }

     }
 }

The only solution I have found so far is to subscribe to the Dispatcher's ShutdownStarted event. Is this a reasonable approach?

this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;

Source: (StackOverflow)

DesignMode with Controls

Has anyone found a useful solution to the DesignMode problem when developing controls?

The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.

The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.

The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.

A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!


Source: (StackOverflow)

'UserControl' constructor with parameters in C#

Call me crazy, but I'm the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the properties are required to actually construct the object, they should go in the constructor. I get two advantages:

  1. I know that when an object is constructed (without error/exception), my object is good.
  2. It helps avoid forgetting to set a certain property.

This mindset is starting to hurt me in regards to form/usercontrol development. Imagine this UserControl:

public partial class MyUserControl : UserControl
{
  public MyUserControl(int parm1, string parm2)
  {
    // We'll do something with the parms, I promise
    InitializeComponent();
  }
}

At designtime, if I drop this UserControl on a form, I get an exception:

Failed to create component 'MyUserControl' ...
System.MissingMethodException - No parameterless constructor defined for this object.

It seems like, to me, the only way around that was to add the default constructor (unless someone else knows a way).

public partial class MyUserControl : UserControl
{
  public MyUserControl()
  {
    InitializeComponent();
  }

  public MyUserControl(int parm1, string parm2)
  {
    // We'll do something with the parms, I promise
    InitializeComponent();
  }
}

The whole point of not including the parameterless constructor was to avoid using it. And I can't even use the DesignMode property to do something like:

public partial class MyUserControl : UserControl
{
  public MyUserControl()
  {
    if (this.DesignMode)
    {
      InitializeComponent();
      return;
    }

    throw new Exception("Use constructor with parameters");
  }
}

This doesn't work either:

if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)

Fine, moving along ...

I have my parameterless constructor, I can drop it on the form, and the form's InitializeComponent will look like this:

private void InitializeComponent()
{
  this.myControl1 = new MyControl();

  // blah, blah
}

And trust me, because I did it (yes, ignoring the comments Visual Studio generated), I tried messing around and I passed parameters to InitializeComponent so that I could pass them to the constructor of MyControl.

Which leads me to this:

public MyForm()
{
  InitializeComponent(); // Constructed once with no parameters

  // Constructed a second time, what I really want
  this.myControl1 = new MyControl(anInt, aString);  
}

For me to use a UserControl with parameters to the constructor, I have to add a second constructor that I don't need? And instantiate the control twice?

I feel like I must be doing something wrong. Thoughts? Opinions? Assurance (hopefully)?


Source: (StackOverflow)

WPF ControlTemplate vs UserControl

I've recently made an UserControl, which took quite a long time, because I had to work with custom Dependency Properties and so on...

Anyways, it was just a bunch of 3 controls: TextBox, Popup with Hierarchical Tree.

Now I realized I could probably write a ControlTemplate only. Hence what is the benefit of using UserControl?


Source: (StackOverflow)