Wednesday, October 21, 2009

Nullable ComboBox.SelectedValue

Here's what I hacked out of the nullable DateTimePicker to work for the SelectedValue property of a ComboBox



        /// <summary>
        /// From BReusable
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="dataSource"></param>
        /// <param name="valueMember"></param>

        /// <remarks>With help from Dan Hanan at http://blogs.interknowlogy.com/danhanan/archive/2007/01/21/10847.aspx</remarks>

        public static void BindNullableSelectedValue(this ComboBox comboBox, BindingSource dataSource, String valueMember)

        {

            
var binding = new Binding(Member.Name<ComboBox>(item=>item.SelectedValue), dataSource, valueMember, true);



            
//OBJECT PROPERTY --> CONTROL VALUE

            binding.Format += ((sender, e) =>

            {

                
Binding b = sender as Binding;



                
if (b != null)

                {

                    
var  cBox = (binding.Control as ComboBox);

                    
if (cBox != null)

                    {

                        
if (e.Value == null)

                        {



                            cBox.SelectedItem=
null;



                        }


                    }



                }

            });

            
// CONTROL VALUE --> OBJECT PROPERTY

            binding.Parse += ((sender, e) =>

            {

                
// e.value is the formatted value coming from the control.
                // we change it to be the value we want to stuff in the object.

                var b = sender as Binding;



                
if (b != null)

                {

                    
var cBox = (b.Control as ComboBox);

                    
if (cBox != null)

                    {

                        e.Value = cBox.SelectedItem !=
null ? cBox.SelectedValue : null;

                    }

                }

            });

            comboBox.DataBindings.Add(binding);



        }




- Formatted via Jeff Atwood's - ModernText Visual Studio Macro

2 comments:

  1. Hey,

    what does the line "Member.Name(item=>item.SelectedValue)" stands for? can't compile because "Member" is unknown.

    king regards

    ReplyDelete
  2. Member.Name comes from http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=ImaginaryDevelopment&DownloadId=6852

    which was designed based on this source: http://stackoverflow.com/questions/1329138/how-to-make-databinding-type-safe-and-support-refactoring

    ReplyDelete