This is a migrated thread and some comments may be shown as answers.

Add ImageButton to GridView

3 Answers 139 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Sean
Top achievements
Rank 1
Sean asked on 16 Jun 2009, 02:13 PM
Hello,
I am attempting to add an image button to each row in the grid.  I have found a couple of old posts that detailed exactly what I am trying to do.  However, when I tried to implement the code I am getting an "Out of Memory" error.  The image that I am trying to load is only 2 KB, and the exception occurs on the first row in the gird, so I wouldn't think this would be an issue.  I can successfully load the image to a Picturebox control on the form without a problem.

In the Form_Load event, I call this method to load the image:

Private Sub LoadAppImages()  
        Dim myAssembly As System.Reflection.Assembly 
        Dim myNamespace As String 
        Dim fileName As String 
 
        myAssembly = System.Reflection.Assembly.GetEntryAssembly  
        myNamespace = myAssembly.GetName.Name  
 
        
        fileName = myNamespace & ".tool_dropdown.png" 
 
        Using stream As System.IO.Stream = myAssembly.GetManifestResourceStream(fileName)  
 
            If stream IsNot Nothing Then 
                _toolsIcon = Image.FromStream(stream)  
            End If 
 
            stream.Close()  
 
        End Using  
 
    End Sub 

Then in the CellFormatting event, I configure the image button:

Private Sub rgLines_CellFormatting(ByVal sender As ObjectByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles rgLines.CellFormatting  
          
        If TypeOf (e.CellElement.ColumnInfo) Is GridViewDataColumn AndAlso _  
            Not TypeOf (e.CellElement.RowElement) Is GridTableHeaderRowElement Then 
 
            Dim column As GridViewDataColumn = CType(e.CellElement.ColumnInfo, GridViewDataColumn)  
 
            If column.FieldName = "TOOLS" Then 
 
                'Check to see if the button has already been added   
                If e.CellElement.Children.Count > 0 Then 
 
                    Exit Sub 
 
                End If 
 
                Dim toolsButton As New RadImageButtonElement  
 
                toolsButton.DisplayStyle = DisplayStyle.Image  
                toolsButton.Image = _toolsIcon  
 
                e.CellElement.Children.Add(toolsButton)  
                ApplyThemeToElement(toolsButton, "ControlDefault")  
 
            End If 
 
        End If 
 
    End Sub 

The error occurs when I call "e.CellElement.Children.Add(toolsButton)". 

Here is the full Stack Trace.  Any ideas what I may be doing wrong?

System.Reflection.TargetInvocationException was unhandled
  Message="Exception has been thrown by the target of an invocation."
  Source="mscorlib"
  StackTrace:
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at Telerik.WinControls.RadControl.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WinFormQuotesGrid.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.OutOfMemoryException
       Message="Out of memory."
       Source="System.Drawing"
       StackTrace:
            at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
            at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData)
            at System.Drawing.Bitmap.MakeTransparent(Color transparentColor)
            at Telerik.WinControls.Primitives.ImagePrimitive.get_Image()
            at Telerik.WinControls.Primitives.ImagePrimitive.OnPropertyChanged(RadPropertyChangedEventArgs e)
            at Telerik.WinControls.RadObject.UpdateEffectiveValue(RadProperty dp, RadPropertyMetadata metadata, Boolean isCoerceValue, Boolean isOldValueValid, Object oldValue, ValueSource oldValueSource, Boolean oldValueIsDeferred, Boolean coerceWithDeferredReference)
            at Telerik.WinControls.RadObject.SetValueCommon(RadProperty dp, Object value, RadPropertyMetadata metadata, Boolean coerceWithDeferredReference)
            at Telerik.WinControls.RadObject.SetValue(RadProperty dp, Object value)
            at Telerik.WinControls.RadObject.BindProperty(RadProperty myProperty, RadObject bindingSourceObject, RadProperty bindingSourceProperty, PropertyBindingOptions propertyBindingOptions)
            at Telerik.WinControls.UI.RadButtonElement.CreateChildElements()
            at Telerik.WinControls.RadElement.EnsureChildElements()
            at Telerik.WinControls.RadElement.InvalidateTotalTransformationReqursively()
            at Telerik.WinControls.RadElement.InvalidateTransformations(Boolean invalidateElement)
            at Telerik.WinControls.RadElement.ChangeCollection(RadElement child, ItemsChangeOperation changeOperation)
            at Telerik.WinControls.RadElementCollection.OnInsertComplete(Int32 index, Object value)
            at System.Collections.CollectionBase.System.Collections.IList.Insert(Int32 index, Object value)
            at Telerik.WinControls.RadElementCollection.Insert(Int32 index, RadElement value)
            at WinFormQuotesGrid.Form1.rgLines_CellFormatting(Object sender, CellFormattingEventArgs e) in C:\projects\ProjectQuote\WinFormQuotesGrid\WinFormQuotesGrid\Form1.vb:line 166
            at Telerik.WinControls.UI.RadGridView.OnCellFormatting(Object sender, CellFormattingEventArgs e)
            at Telerik.WinControls.UI.RadGridView.CallCellFormatting(Object sender, CellFormattingEventArgs e)
            at Telerik.WinControls.UI.GridDataRowElement.UpdateInfo()
            at Telerik.WinControls.UI.GridRowElement.Initialize(GridViewRowInfo rowInfo)
            at Telerik.WinControls.UI.GridTableBodyElement.UpdateRow(Int32 position, GridViewRowInfo rowInfo)
            at Telerik.WinControls.UI.GridTableBodyElement.UpdateRowElements(IEnumerable`1 rows, RectangleF clientRect, Single& y, Int32& position, Int32 startIndex, Int32& added, Single left, Single width)
            at Telerik.WinControls.UI.GridTableBodyElement.ArrangeOverride(SizeF finalSize)
            at Telerik.WinControls.RadElement.ArrangeCore(RectangleF finalRect)
            at Telerik.WinControls.RadElement.Arrange(RectangleF finalRect)
            at Telerik.WinControls.UI.GridTableElement.ArrangeOverride(SizeF finalSize)
            at Telerik.WinControls.RadElement.ArrangeCore(RectangleF finalRect)
            at Telerik.WinControls.RadElement.Arrange(RectangleF finalRect)
            at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayout()
            at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayoutCallback(ILayoutManager manager)
       InnerException:


3 Answers, 1 is accepted

Sort by
0
Victor
Telerik team
answered on 17 Jun 2009, 10:38 AM
Hello Sean,

Thank you for writing. This is related to the way resource streams work. When you get the resource stream and create an object from it, you must not close the stream afterwards. In your case you should simply remove the using block and use the stream without closing or disposing it. Please write back if you need further assistance.

Kind regards,
Victor
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
Sean
Top achievements
Rank 1
answered on 17 Jun 2009, 12:27 PM
Thanks for the response.  Should I be concerned about leaving that memory stream open?  It does implement IDisposable, so shouldn't I be calling that somewhere?

Sean
0
Victor
Telerik team
answered on 17 Jun 2009, 12:51 PM
Hi Sean,

I am afraid that I am not exactly sure whether the stream should be closed. There are many other cases where you have access to objects which implement IDisposable but should not be disposed. One example is the Control.Paint() method. In the event arguments you have a Graphics reference which should not be disposed.

I suggest posting this question in StackOverflow or some other .NET website which you find trustworthy. Please write back if you have other questions.

Kind regards,
Victor
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Tags
GridView
Asked by
Sean
Top achievements
Rank 1
Answers by
Victor
Telerik team
Sean
Top achievements
Rank 1
Share this question
or