שתף באמצעות


Combobox with multiple columns

Question

Wednesday, September 6, 2006 11:43 PM | 1 vote

I'm filling a combobox from a dataset that has three columns, DealerID, DealerName, DealerState.  I can only get one column to display.  Is it possible to show two or more columns in a combobox?  My code follows:

 

adapter.Fill(datList, "tblDealerID"))

Dim drDealer as DataRow

For Each drDealer in datList.Tables("tblDealerID").Rows

cboDealer.Items.Add(drDealer("DealerID"))

Next

All replies (4)

Wednesday, September 6, 2006 11:56 PM ✅Answered | 3 votes

The combobox only handles a single coulmn of displayed data...it does have a displaymember and a valuemember property for binding to the datasource..However if you must display multicolumn in a combo box then you can concantenante you column values:

Dim TheValues as String

For Each drDealer in datList.Tables("tblDealerID").Rows

TheValues = drDealer("DealerID") & " : " & drDealer("DealerName")  & " : " & drDealer("DealerState")

cboDealer.Items.Add(TheValues)

Next

Or you can have

cboDealer.Datasource = tblDealerId

cboDealer.DisplayMember = DealerName

cboDealer.ValueMember = DealerId

 

However with the binding method shown only the dealer name will appear in the combobox

 

 


Friday, January 30, 2009 3:49 PM

hi your help was so helpful i think you are very good programmer and your mulitple column logic into combobox was superb thanks though, i'm just learing vb.net i want in touch with you but i don't know how to post a question and so please if you're kind enough give me your e-mail address i have a small problem while updating data into datagrid it doesn't take new values and gives an error message but please contact me on my e-mail address that is: our.ned@gmail.com

thanks for you help

 


Wednesday, March 2, 2011 6:29 PM

I would create a new user control with the base class combox, and pass to the new MultiComboBox an array of valid header strings as found in the data table.

ListViewColumns = new string(3) {"col1","col3","col5"}

if set, display only the columns in the drop down list as specified, if not, then display all columns as found in the datasource object.

code to follow:

  [ToolboxBitmap(typeof(System.Windows.Forms.ComboBox))]
  public class MultiColumnComboBox : ComboBox
  {
    #region " Private Variables "
    const int columnPadding = 5;
    private float[] columnWidths = new float[0];
    private String[] columnNames = new String[0];
    private int valueMemberColumnIndex = 0;

    private String[] mListViewColumns = new String[0];   // Allow user to define columns
    #endregion

    #region " Public Properties "
    /// <summary>
    /// Define the columns to view in the list box. Default is all columns.
    /// </summary>
    [Browsable(true)]
    [EditorBrowsable(EditorBrowsableState.Always), DefaultValue((string)"(none)"), Description("Indicates the columns to display in drop down list. If (none) display all.")]
    public String[] ListViewColumns
    {
      get { return this.mListViewColumns; }
      set
      {
        this.mListViewColumns = value;
        InitializeColumns();
      }
    }
    public MultiColumnComboBox()
    {
      DrawMode = DrawMode.OwnerDrawVariable;      
    }

    public new DrawMode DrawMode 
    { 
      get
      {
        return base.DrawMode;
      } 
      set
      {
        if (value != DrawMode.OwnerDrawVariable)
        {
          throw new NotSupportedException("Needs to be DrawMode.OwnerDrawVariable");
        }
        base.DrawMode = value;
      }
    }

    public new ComboBoxStyle DropDownStyle
    { 
      get
      {
        return base.DropDownStyle;
      } 
      set
      {
        if (value == ComboBoxStyle.Simple)
        {
          throw new NotSupportedException("ComboBoxStyle.Simple not supported");
        }
        base.DropDownStyle = value;
      }
    }
    #endregion

    protected override void OnDataSourceChanged(EventArgs e)
    {
      base.OnDataSourceChanged(e);

      InitializeColumns();
    }

    protected override void OnValueMemberChanged(EventArgs e)
    {
      base.OnValueMemberChanged(e);

      InitializeValueMemberColumn();
    }

    protected override void OnDropDown(EventArgs e)
    {
      base.OnDropDown(e);
      this.DropDownWidth = (int)CalculateTotalWidth();
    }

 

    private void InitializeColumns()
    {
      //
      // Determine if this will default to show all columns in the datasource.
      // 
      if (this.mListViewColumns.Length==0 )
      {
        try
        {
          PropertyDescriptorCollection propertyDescriptorCollection = DataManager.GetItemProperties();

          columnWidths = new float[propertyDescriptorCollection.Count];
          columnNames = new String[propertyDescriptorCollection.Count];

          for (int colIndex = 0; colIndex < propertyDescriptorCollection.Count; colIndex++)
          {
            String name = propertyDescriptorCollection[colIndex].Name;
            columnNames[colIndex] = name;
          }
        } catch(Exception) {}
      }
      else
      {
        this.columnWidths = new float[this.mListViewColumns.Length];
        this.columnNames = new String[this.mListViewColumns.Length];

        for (int colIndex = 0; colIndex < this.mListViewColumns.Length; colIndex++)
        {
          this.columnNames[colIndex] = this.mListViewColumns[colIndex];
        }
      }
    }

    private void InitializeValueMemberColumn()
    {
      int colIndex = 0;
      foreach (String columnName in columnNames)
      {
        if (String.Compare(columnName, ValueMember, true, CultureInfo.CurrentUICulture) == 0)
        {
          valueMemberColumnIndex = colIndex;
          break;
        }
        colIndex++;
      }
    }

    private float CalculateTotalWidth()
    {
      float totWidth = 0;
      foreach (int width in columnWidths)
      {
        totWidth += (width + columnPadding);
      }
      return totWidth + SystemInformation.VerticalScrollBarWidth;
    }
    
    protected override void OnMeasureItem(MeasureItemEventArgs e)
    {
      base.OnMeasureItem(e);

      if (DesignMode)
        return;

      for (int colIndex = 0; colIndex < columnNames.Length; colIndex++)
      {
        string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex]));
        SizeF sizeF = e.Graphics.MeasureString(item, Font);
        columnWidths[colIndex] = Math.Max(columnWidths[colIndex], sizeF.Width);
      }

      float totWidth = CalculateTotalWidth();

      e.ItemWidth = (int)totWidth;
    }
    /// <summary>
    /// Called when user clicks the down arrow of the combobox.
    /// </summary>
    /// <param name="e"></param>
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
      base.OnDrawItem(e);

      if (DesignMode)
        return;

      e.DrawBackground();

      Rectangle boundsRect = e.Bounds;
      int lastRight = 0;

      using (Pen linePen = new Pen(SystemColors.GrayText))
      {
        using (SolidBrush brush = new SolidBrush(ForeColor))
        {
          if (columnNames.Length == 0)
          {
            e.Graphics.DrawString(Convert.ToString(Items[e.Index]), Font, brush, boundsRect);
          }
          else
          {
            for (int colIndex = 0; colIndex < columnNames.Length; colIndex++)
            {
              string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex]));

              boundsRect.X = lastRight;
              boundsRect.Width = (int)columnWidths[colIndex] + columnPadding;
              lastRight = boundsRect.Right;

              if (colIndex == valueMemberColumnIndex)
              {
                using (Font boldFont = new Font(Font, FontStyle.Bold))
                {
                  e.Graphics.DrawString(item, boldFont, brush, boundsRect);
                }
              }
              else
              {
                e.Graphics.DrawString(item, Font, brush, boundsRect);
              }
              //
              // Draw a line to seperate the columns.
              //
              if (colIndex < columnNames.Length - 1)
              {
                e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, boundsRect.Right, boundsRect.Bottom);
              }
            }
          }
        }
      }

      e.DrawFocusRectangle();
    }
  }

Wednesday, March 2, 2011 9:53 PM

i'm just learing vb.net i want in touch with you but i don't know how to post a question

What do you mean you don't know how to post a question?  You just posted one!