Solved

How to retrieve the Value of the displaymember of a DataGridViewComboboxColumn

Posted on 2016-10-04
2
36 Views
Last Modified: 2016-10-05
I have a reference to a cell of a DataGridViewComboboxColumn
"DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)"
I can get the Value of the ValueMember using "DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value"
But how can I retrieve the Value of the DisplayMember?
0
Comment
Question by:Declan_Basile
2 Comments
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41828576
FormattedValue is the displayed value.  Proof of concept -

Form1.vb -
Imports System.Text

Public Class Form1
	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
		DataGridView1.DataSource = (From i In Enumerable.Range(0, 5) Select New With {.ID = i, .Name = String.Format("Name{0}", i), .Money = CType((i + 9) * 5, Decimal), .BirthDate = DateTime.Now.AddYears(-(i * 9))}).ToList()
	End Sub

	Private Sub OnCellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
		If TypeOf sender Is DataGridView Then
			Dim grid = DirectCast(sender, DataGridView)
			If grid.Rows.Count > 0 And e.Value IsNot Nothing Then
				Dim row = DirectCast(grid.Rows(e.RowIndex), DataGridViewRow)
				Dim column = DirectCast(grid.Columns(e.ColumnIndex), DataGridViewColumn)
				If column.Name.IndexOf("money", StringComparison.OrdinalIgnoreCase) > -1 Then
					e.Value = CType(e.Value, Decimal).ToString("C2")
				ElseIf column.Name.IndexOf("birthdate", StringComparison.OrdinalIgnoreCase) > -1 Then
					e.Value = CType(e.Value, DateTime).ToString("MM/dd/yyyy")
				End If
			End If
		End If
	End Sub

	Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
		If DataGridView1.SelectedRows.Count > 0 Then
			Dim builder As New StringBuilder()
			builder.AppendLine("Values:")
			builder.AppendLine(String.Join("; ", From cell As DataGridViewCell In DataGridView1.SelectedRows(0).Cells Select String.Format("{0}: {1}", DataGridView1.Columns(cell.ColumnIndex).Name, cell.Value)))
			builder.AppendLine()
			builder.AppendLine("Formatted Values:")
			builder.AppendLine(String.Join("; ", From cell As DataGridViewCell In DataGridView1.SelectedRows(0).Cells Select String.Format("{0}: {1}", DataGridView1.Columns(cell.ColumnIndex).Name, cell.FormattedValue)))
			MessageBox.Show(builder.ToString())
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.DataGridView1 = New System.Windows.Forms.DataGridView()
		Me.Button1 = New System.Windows.Forms.Button()
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.SuspendLayout()
		'
		'DataGridView1
		'
		Me.DataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill
		Me.DataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells
		Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
		Me.DataGridView1.Dock = System.Windows.Forms.DockStyle.Top
		Me.DataGridView1.Location = New System.Drawing.Point(0, 0)
		Me.DataGridView1.MultiSelect = False
		Me.DataGridView1.Name = "DataGridView1"
		Me.DataGridView1.RowHeadersVisible = False
		Me.DataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
		Me.DataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
		Me.DataGridView1.Size = New System.Drawing.Size(570, 224)
		Me.DataGridView1.TabIndex = 0
		'
		'Button1
		'
		Me.Button1.Location = New System.Drawing.Point(436, 230)
		Me.Button1.Name = "Button1"
		Me.Button1.Size = New System.Drawing.Size(122, 23)
		Me.Button1.TabIndex = 1
		Me.Button1.Text = "Get Row Values"
		Me.Button1.UseVisualStyleBackColor = True
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(570, 261)
		Me.Controls.Add(Me.Button1)
		Me.Controls.Add(Me.DataGridView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
	Friend WithEvents Button1 As System.Windows.Forms.Button

End Class

Open in new window

Produces the following output -Capture.JPG
-saige-
0
 
LVL 1

Author Closing Comment

by:Declan_Basile
ID: 41830147
Worked great.  Thanks.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now