Golden Rule of Winform Databinding#

Rocky Lhotka had this over on his site:

The Golden Rule of Windows Forms data binding

Never directly interact with a business object while it is data bound - only interact with the bindingsource

http://forums.lhotka.net/forums/thread/22990.aspx

I have to say, I am guilty of doing this, and I didn't even know it was considered a bad practice, but I do recall running into problems with the behavior in getting the UI to refresh as I would want it to.

I also found a nice article talking about how to speed up binding to the datagrid:
 
Categories: Programming | .Net | WinForms
Monday, March 23, 2009 3:08:22 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Problems Extending Winforms Combobox#

On a recent project, one of my developers was trying to extend the combobox in a winforms project.  We wanted to reuse the same combobox in several places. 

The combobox would always have the same objects bound to it, and we wanted a few functions extra functions on the combobox that would centralize some functionality.

So we inherited from combobox, and in the constructor of our class we created the 5 objects that we need in the dropdown and we added them to the combobox items collection.

So far so good.

But we found that when we made a change in the designer for a form that uses this combobox, the designer put stuff in the designer.vb file.  Lines that were trying to add items to our combobox.

It used the .items.AddRange(...) function and tried to add 1 item for every item that we add in the contructor.

Basically it was looking like the designer instantiated the control, and then was trying to serialize the items in the combobox when we would change anything on the form.

This would eventually cause the designer to blow up, as well as a similar error when we tried to run the compiled code.

The solution was elusive and quite a pain.

Some credit needs to go to Andre for his post.

Basically we needed a way to tell in our code if the control was being hosted in the VS designer.  If it was, then we skipped the part where we populated this dropdown.

So first thing we did was create 2 functions to figure out where the control is hosted:

Private Function IsDesignerHosted() As Boolean
    Return Me.IsControlDesignerHosted(Me)
End Function
Private Function IsControlDesignerHosted(ByVal ctrl As Control) As Boolean
    If ctrl IsNot Nothing Then
        If ctrl.Site IsNot Nothing Then
            If ctrl.Site.DesignMode Then
                Return True
            Else
                Return IsControlDesignerHosted(ctrl.Parent)
            End If
        Else
            Return IsControlDesignerHosted(ctrl.Parent)
        End If
    Else
        Return False
    End If
End Function

Then, because it turns out that testing the DesignMode is useless when you are doing the testing from the constructor, so I had to move the databinding into it's own function along with a instance variable to make sure we only do this one time.

Private cbInit As Boolean = False
Private Sub MyControl_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.VisibleChanged
    If Not cbInit Then
        cbInit = True
        If Not Me.IsDesignerHosted Then
            '*** add items here
        End If
    End If
End Sub

There it is!

 

Categories: Programming | .Net | WinForms
Wednesday, October 08, 2008 1:53:28 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Where did my columns go?#

I just noticed this while working on a windows forms .net application.

I made some changes to the underlying business objects that I had bound to a datagridview.  Things looked like they should at runtime, but when I opened up the designer, several of my columns were missing!

After some testing around, I realized that any column that was bound to a property on the object, where I had changed the name of the property, was no longer showing.

I figured it would fail the databind or something, but at least let me change the column details to get things working right!

So I added in fake empty property definitions to the business objects and presto: back come the columns.

After that, I was able to update the databinding field and remove my bogus properties.

 

Categories: Programming | .Net | .Net Framework | WinForms
Wednesday, February 13, 2008 6:15:40 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Right aligning text when printing from a .net program#

In a program I am writing, I need to print directly to a couple of label printers.

My God these things are a pain in the ass to work with, but I will leave that rant to another post.

One thing I ran into was how to right align text when using the DrawString method of the System.Drawing.Graphics class off of the PrintPageEventArgs.

The solutions I was coming across seemed about as bad as I was expecting.

They involved measuring the width of the line of string using some System.Drawing.Graphics.MeasureString to figure out the length, and then dynamically position the text to make it appear right aligned.  So what that means is that for short text, X would be greater and for long text X would be less.

Fortunately, I came across the most simple solution:

Dim s As New StringFormat()
s.Alignment = StringAlignment.Far

e.Graphics.DrawString("por que?", New Font("Tahoma", 8), Brushes.Black, 50, 50, s)

Very simple.  But you have to wonder, why did MS pick "Far" as the alignment name instead of "Right", as you would expect.  Maybe "Far" is more of a graphics term for alignment?  Who knows.

 

Categories: Programming | .Net | .Net Framework | WinForms
Monday, August 06, 2007 2:44:24 AM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Dealing with WinForms Combobox and name/value items.#

I just read this article on aspalliance.com by Sandeep Archarya.

I think the article had 2 main points.  One was that databinding a combobox is not "bug free" because the act of manually databinding to a combobox causes the SelectedIndexChanged event to fire.  The second point was to show how to create a simple namevalue class to be added to the combobox items collection to get around the "problem" of combobox's taking an object as the item in it's list (as opposed to a name value pair).

I would point out the following:

First, I am not sure that I would call the SelectedIndexChanged event firing a bug.  When you manually databind a list, the first item become selected by default, and thus the selectedindex HAS changed, from -1 to 0.

Second, if you consider this a problem you can get around it a couple different ways.

1) Don't use manual databinding.

In the designer, select a datasource or create a new one.  I created a simple employee object and created an object datasource for this employee.  This creates a EmployeeBindingSource object that I bind my employee list to.  Using this method, I didn't experience the SelectedIndexChanged event firing on the databind.

Private list As New System.Collections.Generic.List(Of employee)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    '*** create some fake employee objects
   For i As Integer = 70 To 80
      list.Add(New employee(i, Chr(i)))
   Next

    '*** this will populate our control (Combobox1)
   Me.EmployeeBindingSource.DataSource = list

End Sub

2) You can use manual databinding, and manually detach and attach the event handler for this event.

Private list As New System.Collections.Generic.List(Of employee)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
    '*** create some fake employee objects
   For i As Integer = 70 To 80
      list.Add(New employee(i, Chr(i)))
   Next

    '*** remove the handler
    RemoveHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
    '*** databind
    Me.ComboBox1.ValueMember = "id"
    Me.ComboBox1.DisplayMember = "name"
    Me.ComboBox1.DataSource = list
    '*** add the handler back
    AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
End Sub

 

Categories: .Net | .Net Framework | DataBinding | WinForms
Friday, November 10, 2006 4:32:43 PM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

Select DataSource and Visual Studio Errors#

I recently ran into a nebulous problem when creating a windows app with vs.net 2005.

I would select the DataBindings or DataSource properties from the proeprties window (click the dropdown) and VS would give me an "Object reference not set to an instance of an object" error.

Fantastic!

I finally figured out the problem was caused by a recent rename of a misspelled class.

This class was being used by one of the datasources.  As soon as I changed the name of that class, the datasource became invalid, and I guess when VS tries to get a list of the these datasources for the dropdown it just blows up.

Once I deleted the problematic datasource everything went back to normal.

Categories: Programming | .Net | VS.Net | WinForms
Tuesday, August 01, 2006 9:25:40 PM (Central Daylight Time, UTC-05:00) #    Comments [2]  | 

 

Creating a Sortable BindingList#

This article from MSDN talks about custom databinding, but specifically it talks about the issues raised when you are trying to databind a custom collection to a datagridview.

Using a List<T> will work, but when all is said and done you lose some nice features such as sorting.

Categories: Programming | .Net | .Net Framework | ASP.Net | WinForms
Wednesday, May 17, 2006 8:43:51 AM (Central Daylight Time, UTC-05:00) #    Comments [1]  | 

 

ReportViewer in LocalReport Mode With Subreports And Business Objects#

There are not many good examples of how to do stuff like this.  So the article below was all the more helpful when I was building a somewhat complex report.

http://www.codeproject.com/dotnet/AdoNetForOopPart2.asp?df=100&forumid=258341&select=1482558&msg=1482558

 

Categories: Programming | .Net | WinForms | Reporting
Wednesday, May 10, 2006 9:07:29 PM (Central Daylight Time, UTC-05:00) #    Comments [0]  | 

 

Sending an App to the SysTray#
This article shows how to send a .net application to the systray.
Categories: Programming | .Net | WinForms
Tuesday, February 03, 2004 11:08:03 AM (Central Standard Time, UTC-06:00) #    Comments [0]  | 

 

All content © 2010, Christopher May, Inc
Open Job Positions
On this page
Google Ads
This site
Calendar
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: