Question

ComboBox in a DataGrid column

Asked by: Milos

How can I put a ComboBox in a column of a data grid?

ComboBox data source needs to be a table filtered by the ID field in the same row of the data grid (values are different for each row).

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-26 at 05:52:59ID20862953
Tags

datagrid

,

combobox

Topic

C# Programming Language

Participating Experts
3
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ComboBox in DataGrid
    Dear advisors ! I want to add a ComboBox into DataGrid. The user could choice a value in that comboBox to replace into Table. Could you help me to do like that ? Thank for all comment
  2. Combobox filter?
    Hi I would like to filter a combobox based on another combobox selection. I have a combobox column inside a datagrid1, in datagrid2 I have another combobox column. the combox are fills from dataviews. I want to filter the dataview for combobox in datagri 2 based on the v...
  3. DataGrid and ComboBox
    Hi, please I would like some help in a little problem ... I have a datagrid binded to a dataset, and there are fields in this grid that are foreign keys from other tables, so I would like to be able to choose between these values by using a comboBox in the datagrid .. How can...
  4. Combobox Filtering
    I have a Windows Application form that contains a datagrid. One of the columns on the populating datagrid is called "StatusCode" Inside this column, there can only contain 4 values. Tagged Inactive Out Inhouse I want to have a combobox for the user to cho...
  5. Filter datagrid with combobox
    Hi, I am writing a VB.NET application. On the form I have a combobox called cboClients and a DataGrid called dGridJobs. I want to filter the contents in the datagdrid by using the data in the combobox. Can anyone give me an example on how to do this? Thanks Vyyk

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: DaniProPosted on 2004-01-26 at 06:11:50ID: 10200772

 

by: MilosPosted on 2004-01-26 at 06:30:57ID: 10200861

I've tried this and I have only one problem.

If I don't filter ComboBox source table for every row in DataGrid everything works fine, but if I do, I see only the value of the active cell in ComboBox column. Other cels in ComboBox column are blank because i filtered the source table by active row and there is no value to find for other rows.

How can I display all the values in ComboBox column while ComboBox source table is filtered by the current row?

 

by: DaniProPosted on 2004-01-26 at 07:04:39ID: 10200951

I think that the best way is that you create a DataView for each row in your DataGrid and use these DataViews like datasource in your DataGrid (one for each row)

 

by: MilosPosted on 2004-01-26 at 07:46:40ID: 10201251

Ok, how?

 

by: DaniProPosted on 2004-01-26 at 08:12:54ID: 10201455

You can create a method that return a DataView of your DataSet and use it when you must assign the datasoruce to your combobox

private DataView MakeDataView(DataSet ds, string parm)
{
      DataView dv = new DataView(ds.Tables["Suppliers"], parm, "CompanyName", DataViewRowState.CurrentRows);
      dv.AllowEdit = true;
      dv.AllowNew = true;
      dv.AllowDelete = true;
      return dv;
}

 

by: pjapiksePosted on 2004-01-26 at 12:42:51ID: 10203877

I think what you really want is a combo box TEXT column - it will show as a normal datagridtextbox when the field does not have the focus, but as a combo box when the field does have the focus.  FTP has a good sample, I will dig up the link.

 

by: pjapiksePosted on 2004-01-26 at 12:45:22ID: 10203892

ok, couldn't find the link right away, but here is the listing from the Visual Studio article:

(c) 2003 Visual Studio Magazine
Fawcette Technical Publications

VB.NET      Create a Combo Box Column
Listing 1      You can make a DataGrid column show and hide a combo box, instead of the classic text box, by deriving from the DataGridTextBoxColumn class to manage events such as Edit and Leave.

Public Class DataGridComboBoxColumn
      Inherits DataGridTextBoxColumn

      Public MyCombo As ComboBox

      Public Sub New()
            MyBase.New()

            MyCombo = New ComboBox
            AddHandler MyCombo.Leave, New EventHandler( _
                  AddressOf LeaveComboBox)

      End Sub

      Protected Overloads Overrides Sub Edit(ByVal _
            source As CurrencyManager, ByVal rowNum _
            As Integer, ByVal bounds As Rectangle, _
            ByVal readOnly1 As Boolean, ByVal _
            instantText As String, ByVal cellIsVisible As Boolean)
            MyBase.Edit(source, rowNum, bounds, _
                  readOnly1, instantText, cellIsVisible)

            MyCombo.Parent = Me.TextBox.Parent
            MyCombo.Location = Me.TextBox.Location
            MyCombo.Size = New Size(Me.TextBox.Size.Width, _
                  MyCombo.Size.Height)
            MyCombo.Text = Me.TextBox.Text
            Me.TextBox.Visible = False
            MyCombo.Visible = True
            MyCombo.BringToFront()
            MyCombo.Focus()

      End Sub

      Private Sub LeaveComboBox(ByVal sender _
            As Object, ByVal e As EventArgs)
            MyCombo.Hide()
      End Sub
End Class

VB.NET      Commit User Changes
Listing 2      This DataGrid combo box column implementation commits changes the user enters through the combo box to the data source.

Public Class DataGridComboBoxColumn
      Inherits DataGridTextBoxColumn

      Public MyCombo As DataGridComboBox
      Private m_isEditing As Boolean

      Public Sub New()
            MyBase.New()

            MyCombo = New DataGridComboBox
            m_isEditing = False

            AddHandler MyCombo.Leave, New _
                  EventHandler(AddressOf LeaveComboBox)
            AddHandler MyCombo.SelectionChangeCommitted, New _
                  EventHandler(AddressOf OnSelectionChangeCommitted)
      End Sub

      Protected Overloads Overrides Sub Edit(ByVal source As _
            CurrencyManager, ByVal rowNum As Integer, ByVal _
            bounds As Rectangle, ByVal readOnly1 As Boolean, _
            ByVal instantText As String, ByVal cellIsVisible As _
            Boolean)
            MyBase.Edit(source, rowNum, bounds, _
                  readOnly1, instantText, cellIsVisible)

            MyCombo.Parent = Me.TextBox.Parent
            MyCombo.Location = Me.TextBox.Location
            MyCombo.Size = New Size(Me.TextBox.Size.Width, _
                  MyCombo.Size.Height)
            MyCombo.Text = Me.TextBox.Text
            Me.TextBox.Visible = False
            MyCombo.Visible = True
            MyCombo.BringToFront()
            MyCombo.Focus()

      End Sub

      Private Sub LeaveComboBox(ByVal sender As _
            Object, ByVal e As EventArgs)
            MyCombo.Hide()
      End Sub

      Protected Overloads Overrides Function Commit(ByVal _
            dataSource As CurrencyManager, ByVal rowNum As _
            Integer) As Boolean

            If m_isEditing Then
                  m_isEditing = False
                  SetColumnValueAtRow(dataSource, rowNum, _
                        MyCombo.Text)
            End If
            Return True

      End Function
      Private Sub OnSelectionChangeCommitted(ByVal sender As _
            Object, ByVal e As EventArgs)

            m_isEditing = True
      MyBase.ColumnStartedEditing(sender)

      End Sub
End Class

VB.NET      Color a DataGrid Cell
Listing 3      You can customize a DataGrid cell's look by overriding the Paint event to change the values of the cell's background and foreground colors.

Public Class DataGridColoredTextBoxColumn
      Inherits DataGridTextBoxColumn

      Public Sub New(ByVal prop As PropertyDescriptor, _
            ByVal format As String, ByVal isDefault As Boolean)
            MyBase.New(prop, format, isDefault)
      End Sub

      Protected Overloads Overrides Sub Paint(ByVal g As _
            Graphics, ByVal bounds As Rectangle, ByVal source As _
            CurrencyManager, ByVal rowNum As Integer, ByVal _
            backBrush As Brush, ByVal foreBrush As Brush, ByVal _
            alignToRight As Boolean)

            Dim obj As Object

            Try
                  obj = Me.GetColumnValueAtRow(source, rowNum)
                  If (Not (obj) Is Nothing) Then
                        Dim i As Integer
                        i = CType(obj, Integer)
                        If i < 0 Then
                              backBrush = New SolidBrush(Color.Red)
                              foreBrush = New SolidBrush(Color.White)
                        End If
                  End If

            Catch ex As Exception

            Finally
                  MyBase.Paint(g, bounds, source, rowNum, backBrush, _
                        foreBrush, alignToRight)
            End Try
      End Sub
End Class

C#      Make a Singleton App
Listing 4      The named Mutex serves as a simple cross-process communication mechanism when you use the SingletonApp class to implement a singleton application. If the named Mutex is unowned, SingletonApp launches the app. Otherwise, it simply returns, causing the application to terminate because no window is pumping messages, and the Main method returns.

public class SingletonApp
{
      static Mutex m_Mutex;
      public static void Run(Form mainForm)
      {
            if(IsFirstInstance())
            {
                  Application.ApplicationExit += new
                        EventHandler(OnExit);
                  Application.Run(mainForm);
            }
      }
      //Other versions of Run()
      static bool IsFirstInstance()
      {
            m_Mutex = new Mutex(false,"SingletonApp Mutex");

            bool owned = false;
            owned = m_Mutex.WaitOne(TimeSpan.Zero,false);
            return owned ;
      }
      static void OnExit(object sender,EventArgs args)
      {
            m_Mutex.ReleaseMutex();
            m_Mutex.Close();
      }
}
public class MyForm : Form
{
   Label m_Label;

      public MyForm()
      {
            InitializeComponent();
      }
      private void InitializeComponent()
      {...}
      static void Main()
      {
            SingletonApp.Run(new MyForm());
      }
}

 

by: pjapiksePosted on 2004-01-26 at 12:47:48ID: 10203912

 

by: TheAvengerPosted on 2004-01-27 at 00:23:18ID: 10207678

This is one combo box column that I initially took from www.codeproject.com and then fixed some stuff in it. It works fine but I don't know if it will work with your filtering (which I did not understand quite):

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using System.Collections;
using System.Diagnostics;
using System.Reflection;

namespace AdvancedControls
{
      /// <summary>
      /// Implementation of a ComboBox as a column in a DataGrid
      /// </summary>
      public class DataGridDataBoundComboBoxColumn : DataGridTextBoxColumn
      {
            private ComboBox internalComboBox = new ComboBox();
            private bool currentlyInEdit = false;
            private CurrencyManager source = null;
            private int rowNum = -1;
            private AdvancedDataGrid dataGrid = null;

            #region Properties
            private object nullValue = DBNull.Value;
            /// <summary>
            /// Gives a value that will be considered null and will be replaced for showing by NullValue
            /// </summary>
            public object NullValue
            {
                  set {this.nullValue = value;}
                  get {return this.nullValue;}
            }

            private object nullCorrespondingValue = null;
            /// <summary>
            /// Gives a value that will replace the null values (given by NullValue) for showing
            /// </summary>
            public object NullCorrespondingValue
            {
                  set {this.nullCorrespondingValue = value;}
                  get {return this.nullCorrespondingValue;}
            }

            public object DataSource
            {
                  set
                  {
                        // If the display member or value member is wrong,
                        // this line will clear it
                        this.internalComboBox.DataSource = value;
                        SetComboBoxDropDownWidth();
                  }
                  get { return this.internalComboBox.DataSource; }
            }
            public string DisplayMember
            {
                  set
                  {
                        this.internalComboBox.DisplayMember = value;
                        SetComboBoxDropDownWidth();
                  }
                  get { return this.internalComboBox.DisplayMember; }
            }
            public string ValueMember
            {
                  set {this.internalComboBox.ValueMember = value; }
                  get { return this.internalComboBox.ValueMember; }
            }
            #endregion
            
            #region Construction
            public DataGridDataBoundComboBoxColumn () : base()
            {
                  this.internalComboBox.Visible = false;
                  this.internalComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                  // Some events that guarantee correct working
                  this.internalComboBox.LostFocus += new EventHandler (OnInternalComboBoxLostFocus);
            }
            #endregion
            
            #region Event handlers for the combo box
            private void OnInternalComboBoxLostFocus (object sender, EventArgs e)
            {
                  if ((sender is DataGrid && !this.internalComboBox.Focused) ||
                        sender == this.internalComboBox)
                  {
                        if (this.currentlyInEdit)
                              Commit (this.source, this.rowNum);
                  }
            }
            #endregion

            #region Key management
            /// <summary>
            /// Handles opening and closing of the ComboBox with the keyboard
            /// For this function to work, the data grid should be of type AdvancedDataGrid
            /// </summary>
            /// <param name="msg"></param>
            /// <param name="keyData"></param>
            /// <returns></returns>
            public bool ProcessCmdKey(ref Message msg, Keys keyData)
            {
                  if (!this.currentlyInEdit)
                        return false;

                  if (keyData == Keys.Down)
                  {
                        // Try to select next or the first item
                        if (this.internalComboBox.SelectedIndex < this.internalComboBox.Items.Count - 1)
                              this.internalComboBox.SelectedIndex++;
                        else if (this.internalComboBox.Items.Count > 0)
                              this.internalComboBox.SelectedIndex = 0;
                        return true;
                  }
                  else if (keyData == Keys.Up)
                  {
                        // Try to select previous or the last item
                        if (this.internalComboBox.SelectedIndex > 0)
                              this.internalComboBox.SelectedIndex--;
                        else if (this.internalComboBox.Items.Count > 0)
                              this.internalComboBox.SelectedIndex = this.internalComboBox.Items.Count - 1;
                        return true;
                  }
                  else if ((keyData == (Keys.Up | Keys.Alt) ||
                        keyData == (Keys.Down | Keys.Alt)) &&
                        !this.internalComboBox.DroppedDown)
                  {
                        this.internalComboBox.DroppedDown = true;
                        return true;
                  }
                        // Keys.Down | Keys.Alt work automatically if DropedDown
                  else if ((keyData == Keys.Enter || keyData == (Keys.Up | Keys.Alt)) &&
                        this.internalComboBox.DroppedDown)
                  {
                        HideDropDown();
                        return true;
                  }
                  else if (keyData == Keys.Escape)
                  {
                        Abort (this.rowNum);
                        return true;
                  }

                  return false;
            }
            #endregion

            #region Overriden methods
            
            protected override object GetColumnValueAtRow (CurrencyManager source, int rowNum)
            {
                  object val = base.GetColumnValueAtRow (source, rowNum);
                  // Check for the null value
                  if (Object.Equals (val, this.NullValue) && this.NullCorrespondingValue != null)
                        val = this.NullCorrespondingValue;

                  foreach (object o in this.internalComboBox.Items)
                  {
                        object oVal = GetValueMember (o);
                        if ((oVal == null && val == null) ||
                              (oVal != null && oVal.Equals (val)))
                              return GetDisplayMember (o);
                  }
                  return DBNull.Value;
            }

            protected override void Abort(int rowNum)
            {
                  // If in read only mode, just follow the basic methods
                  if (this.DataGridTableStyle.DataGrid.ReadOnly || this.ReadOnly ||
                        (this.DataGridTableStyle.DataGrid.DataSource is DataView &&
                        !((DataView)this.DataGridTableStyle.DataGrid.DataSource).AllowEdit))
                  {
                        base.Abort (rowNum);
                        return;
                  }

                  if(this.currentlyInEdit)
                  {
                        this.currentlyInEdit = false;
                        this.source = null;
                        this.rowNum = -1;
                        this.internalComboBox.Hide();
                        if (this.internalComboBox.DroppedDown)
                              HideDropDown();
                  }
            }

            protected override bool Commit(CurrencyManager dataSource,int rowNum)
            {
                  // If in read only mode, just follow the basic methods
                  if (this.DataGridTableStyle.DataGrid.ReadOnly || this.ReadOnly ||
                        (this.DataGridTableStyle.DataGrid.DataSource is DataView &&
                        !((DataView)this.DataGridTableStyle.DataGrid.DataSource).AllowEdit))
                        return base.Commit(dataSource, rowNum);

                  if(this.currentlyInEdit)
                  {
                        object selValue = this.internalComboBox.SelectedValue;
                        if (selValue == null || Object.Equals (selValue, this.NullCorrespondingValue))
                              selValue = this.NullValue;
                        SetColumnValueAtRow(dataSource, rowNum, selValue);

                        this.currentlyInEdit = false;
                        this.source = null;
                        this.rowNum = -1;
                        this.internalComboBox.Hide();
                        if (this.internalComboBox.DroppedDown)
                              HideDropDown();
                  }

                  return true;
            }
            
            protected override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
            {
                  // If in read only mode, just follow the basic methods
                  if (this.DataGridTableStyle.DataGrid.ReadOnly || this.ReadOnly ||
                        (this.DataGridTableStyle.DataGrid.DataSource is DataView &&
                        !((DataView)this.DataGridTableStyle.DataGrid.DataSource).AllowEdit))
                  {
                        base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
                        return;
                  }

                  if (this.currentlyInEdit)
                        return;

                  if(!cellIsVisible)
                        return;

                  // Important: show it before setting the selected value
                  // otherwise in some cases the value from the previous edit is returned
                  // (when the drop down is open with the mouse, a new value is pointed
                  // and Tab is pressed)
                  this.internalComboBox.Bounds = bounds;
                  this.internalComboBox.Show();
                  
                  // Get the underlying value
                  // The current implementation of GetColumnValueAtRow will return the DisplayMember
                  object val = base.GetColumnValueAtRow (source, rowNum);
                  // Check for the null value
                  if (Object.Equals (val, this.NullValue) && this.NullCorrespondingValue != null)
                        val = this.NullCorrespondingValue;

                  if (val == null || val == DBNull.Value)
                        if (this.internalComboBox.Items.Count > 0)
                              this.internalComboBox.SelectedIndex = 0;
                        else
                              this.internalComboBox.SelectedIndex = -1;
                  else
                        this.internalComboBox.SelectedValue = val;
                  
                  this.currentlyInEdit = true;
                  this.source = source;
                  this.rowNum = rowNum;

                  ColumnStartedEditing (this.internalComboBox);
            }

            protected override int GetMinimumHeight()
            {
                  return this.internalComboBox.PreferredHeight + 1;
            }

            protected override void SetDataGridInColumn(DataGrid value)
            {
                  base.SetDataGridInColumn (value);

                  if (value == this.dataGrid)
                        return;

                  Debug.Assert (value != null);
                  Debug.Assert (value is AdvancedDataGrid,"The used data grid should be of type AdvancedDataGrid");

                  if (this.dataGrid != null)
                  {
                        this.dataGrid.Controls.Remove (this.internalComboBox);
                        this.dataGrid.LostFocus -= new EventHandler (OnInternalComboBoxLostFocus);
                  }

                  this.dataGrid = (AdvancedDataGrid)value;

                  this.dataGrid.Controls.Add(this.internalComboBox);
                  // Some events that guarantee correct working
                  this.dataGrid.LostFocus += new EventHandler (OnInternalComboBoxLostFocus);
            }
            #endregion

            #region Helper functions
            private void HideDropDown()
            {
                  // Unknown why, the value is lost when DroppedDown is set to false
                  object val = this.internalComboBox.SelectedValue;
                  this.internalComboBox.DroppedDown = false;
                  this.internalComboBox.SelectedValue = val;
            }
            private object GetMember (object o, string member)
            {
                  DataRow row = null;
                  if (o is DataRowView)
                        row = ((DataRowView)o).Row;
                  if (o is DataRow)
                        row = (DataRow)o;
                  if (row != null)
                  {
                        object ret = row[member];
                        if (ret == null)
                              return DBNull.Value;
                        else
                              return ret;
                  }
                  else
                  {
                        PropertyInfo pi = o.GetType().GetProperty (member);
                        Debug.Assert (pi != null);
                        return pi.GetValue (o, null);
                  }
            }
            
            private string GetDisplayMember (object o)
            {
                  if (o == null || o == DBNull.Value)
                        return this.NullText;
                  object val = GetMember (o, this.internalComboBox.DisplayMember);
                  if (val == null || val == DBNull.Value)
                        return this.NullText;
                  else
                        return val.ToString();
            }

            private object GetValueMember (object o)
            {
                  return GetMember (o, this.internalComboBox.ValueMember);
            }

            /// <summary>
            /// Sets the DropDownWidth property of the combo box if all needed
            /// properties are already set
            /// </summary>
            private void SetComboBoxDropDownWidth()
            {
                  if (this.internalComboBox.DataSource == null ||
                        this.internalComboBox.DisplayMember == null ||
                        this.internalComboBox.DisplayMember == String.Empty)
                        return;

                  Graphics g = this.internalComboBox.CreateGraphics ();
                  float w = 0;
                  foreach (object o in this.internalComboBox.Items)
                        w = Math.Max (w, g.MeasureString (GetDisplayMember (o),
                              this.internalComboBox.Font).Width);
                  if (w > 0)
                        this.internalComboBox.DropDownWidth = (int)(w + 0.5);
            }
            #endregion
      }
}

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...