DataGridViewComboBoxColumn Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Represents a column of DataGridViewComboBoxCell objects.
public ref class DataGridViewComboBoxColumn : System::Windows::Forms::DataGridViewColumn
[System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn.bmp")]
public class DataGridViewComboBoxColumn : System.Windows.Forms.DataGridViewColumn
[System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn")]
public class DataGridViewComboBoxColumn : System.Windows.Forms.DataGridViewColumn
[<System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn.bmp")>]
type DataGridViewComboBoxColumn = class
inherit DataGridViewColumn
[<System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn")>]
type DataGridViewComboBoxColumn = class
inherit DataGridViewColumn
Public Class DataGridViewComboBoxColumn
Inherits DataGridViewColumn
- Inheritance
- Attributes
Examples
The following code example demonstrates how to use a DataGridViewComboBoxColumn to aid in entering data into the TitleOfCourtesy
column.
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Xml.dll>
#using <System.EnterpriseServices.dll>
#using <System.Transactions.dll>
using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;
using namespace System::Collections::Generic;
using namespace System::Drawing;
public ref class Employees : public Form
{
private:
DataGridView^ DataGridView1;
private:
DataGridView^ DataGridView2;
public:
[STAThread]
static void Main()
{
try
{
Application::EnableVisualStyles();
Application::Run(gcnew Employees());
}
catch (Exception^ e)
{
MessageBox::Show(e->Message + e->StackTrace);
}
}
private:
Dictionary<String^, bool>^ inOffice;
public:
Employees()
{
DataGridView1 = gcnew DataGridView();
DataGridView2 = gcnew DataGridView();
connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";
inOffice = gcnew Dictionary<String^, bool>;
this->Load += gcnew EventHandler(this, &Employees::Form1_Load);
}
private:
void Form1_Load(System::Object^ /*sender*/, System::EventArgs^ /*e*/)
{
try
{
SetUpForm();
SetUpDataGridView1();
SetUpDataGridView2();
}
catch (SqlException^)
{
MessageBox::Show("The connection string <"
+ connectionString
+ "> failed to connect. Modify it "
+ "to connect to a Northwind database accessible to "
+ "your system.",
"ERROR", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
Application::Exit();
}
}
private:
void SetUpForm()
{
Size = System::Drawing::Size(800, 600);
FlowLayoutPanel^ flowLayout = gcnew FlowLayoutPanel();
flowLayout->FlowDirection = FlowDirection::TopDown;
flowLayout->Dock = DockStyle::Fill;
Controls->Add(flowLayout);
flowLayout->Controls->Add(DataGridView1);
flowLayout->Controls->Add(DataGridView2);
}
private:
void SetUpDataGridView2()
{
DataGridView2->Dock = DockStyle::Bottom;
DataGridView2->TopLeftHeaderCell->Value = "Sales Details";
DataGridView2->RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders;
}
private:
void SetUpDataGridView1()
{
//DataGridView1.DataError += new
// DataGridViewDataErrorEventHandler(DataGridView1_DataError);
DataGridView1->CellContentClick += gcnew
DataGridViewCellEventHandler(this, &Employees::DataGridView1_CellContentClick);
DataGridView1->CellValuePushed += gcnew
DataGridViewCellValueEventHandler(this, &Employees::DataGridView1_CellValuePushed);
DataGridView1->CellValueNeeded += gcnew
DataGridViewCellValueEventHandler(this, &Employees::DataGridView1_CellValueNeeded);
// Virtual mode is turned on so that the
// unbound DataGridViewCheckBoxColumn will
// keep its state when the bound columns are
// sorted.
DataGridView1->VirtualMode = true;
DataGridView1->AutoSize = true;
DataGridView1->DataSource = Populate("SELECT * FROM Employees");
DataGridView1->TopLeftHeaderCell->Value = "Employees";
DataGridView1->RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode::AutoSizeToAllHeaders;
DataGridView1->ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode::AutoSize;
DataGridView1->AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode::AllCells;
DataGridView1->AllowUserToAddRows = false;
DataGridView1->AllowUserToDeleteRows = false;
// The below autogenerated column is removed so
// a DataGridViewComboboxColumn could be used instead.
DataGridView1->Columns->Remove(ColumnName::TitleOfCourtesy.ToString());
DataGridView1->Columns->Remove(ColumnName::ReportsTo.ToString());
AddLinkColumn();
AddComboBoxColumns();
AddButtonColumn();
AddOutOfOfficeColumn();
}
private:
void AddComboBoxColumns()
{
DataGridViewComboBoxColumn^ comboboxColumn;
comboboxColumn = CreateComboBoxColumn();
SetAlternateChoicesUsingDataSource(comboboxColumn);
comboboxColumn->HeaderText = "TitleOfCourtesy (via DataSource property)";
DataGridView1->Columns->Insert(0, comboboxColumn);
comboboxColumn = CreateComboBoxColumn();
SetAlternateChoicesUsingItems(comboboxColumn);
comboboxColumn->HeaderText = "TitleOfCourtesy (via Items property)";
// Tack this example column onto the end.
DataGridView1->Columns->Add(comboboxColumn);
}
private:
void AddLinkColumn()
{
DataGridViewLinkColumn^ links = gcnew DataGridViewLinkColumn();
links->UseColumnTextForLinkValue = true;
links->HeaderText = ColumnName::ReportsTo.ToString();
links->DataPropertyName = ColumnName::ReportsTo.ToString();
links->ActiveLinkColor = Color::White;
links->LinkBehavior = LinkBehavior::SystemDefault;
links->LinkColor = Color::Blue;
links->TrackVisitedState = true;
links->VisitedLinkColor = Color::YellowGreen;
DataGridView1->Columns->Add(links);
}
private:
void SetAlternateChoicesUsingItems(
DataGridViewComboBoxColumn^ comboboxColumn)
{
comboboxColumn->Items->AddRange("Mr.", "Ms.", "Mrs.", "Dr.");
}
private:
DataGridViewComboBoxColumn^ CreateComboBoxColumn()
{
DataGridViewComboBoxColumn^ column =
gcnew DataGridViewComboBoxColumn();
{
column->DataPropertyName = ColumnName::TitleOfCourtesy.ToString();
column->HeaderText = ColumnName::TitleOfCourtesy.ToString();
column->DropDownWidth = 160;
column->Width = 90;
column->MaxDropDownItems = 3;
column->FlatStyle = FlatStyle::Flat;
}
return column;
}
private:
void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn^ comboboxColumn)
{
{
comboboxColumn->DataSource = RetrieveAlternativeTitles();
comboboxColumn->ValueMember = ColumnName::TitleOfCourtesy.ToString();
comboboxColumn->DisplayMember = comboboxColumn->ValueMember;
}
}
private:
DataTable^ RetrieveAlternativeTitles()
{
return Populate("SELECT distinct TitleOfCourtesy FROM Employees");
}
String^ connectionString;
private:
DataTable^ Populate(String^ sqlCommand)
{
SqlConnection^ northwindConnection = gcnew SqlConnection(connectionString);
northwindConnection->Open();
SqlCommand^ command = gcnew SqlCommand(sqlCommand, northwindConnection);
SqlDataAdapter^ adapter = gcnew SqlDataAdapter();
adapter->SelectCommand = command;
DataTable^ table = gcnew DataTable();
adapter->Fill(table);
return table;
}
// Using an enum provides some abstraction between column index
// and column name along with compile time checking, and gives
// a handy place to store the column names.
enum class ColumnName
{
EmployeeID,
LastName,
FirstName,
Title,
TitleOfCourtesy,
BirthDate,
HireDate,
Address,
City,
Region,
PostalCode,
Country,
HomePhone,
Extension,
Photo,
Notes,
ReportsTo,
PhotoPath,
OutOfOffice
};
private:
void AddButtonColumn()
{
DataGridViewButtonColumn^ buttons = gcnew DataGridViewButtonColumn();
{
buttons->HeaderText = "Sales";
buttons->Text = "Sales";
buttons->UseColumnTextForButtonValue = true;
buttons->AutoSizeMode =
DataGridViewAutoSizeColumnMode::AllCells;
buttons->FlatStyle = FlatStyle::Standard;
buttons->CellTemplate->Style->BackColor = Color::Honeydew;
buttons->DisplayIndex = 0;
}
DataGridView1->Columns->Add(buttons);
}
private:
void AddOutOfOfficeColumn()
{
DataGridViewCheckBoxColumn^ column = gcnew DataGridViewCheckBoxColumn();
{
column->HeaderText = ColumnName::OutOfOffice.ToString();
column->Name = ColumnName::OutOfOffice.ToString();
column->AutoSizeMode =
DataGridViewAutoSizeColumnMode::DisplayedCells;
column->FlatStyle = FlatStyle::Standard;
column->ThreeState = true;
column->CellTemplate = gcnew DataGridViewCheckBoxCell();
column->CellTemplate->Style->BackColor = Color::Beige;
}
DataGridView1->Columns->Insert(0, column);
}
private:
void PopulateSales(DataGridViewCellEventArgs^ buttonClick)
{
String^ employeeID = DataGridView1->Rows[buttonClick->RowIndex]
->Cells[ColumnName::EmployeeID.ToString()]->Value->ToString();
DataGridView2->DataSource = Populate("SELECT * FROM Orders WHERE EmployeeID = " + employeeID);
}
#pragma region "SQL Error handling"
private:
void DataGridView1_DataError(Object^ sender, DataGridViewDataErrorEventArgs^ anError)
{
MessageBox::Show("Error happened " + anError->Context.ToString());
if (anError->Context == DataGridViewDataErrorContexts::Commit)
{
MessageBox::Show("Commit error");
}
if (anError->Context == DataGridViewDataErrorContexts::CurrentCellChange)
{
MessageBox::Show("Cell change");
}
if (anError->Context == DataGridViewDataErrorContexts::Parsing)
{
MessageBox::Show("parsing error");
}
if (anError->Context == DataGridViewDataErrorContexts::LeaveControl)
{
MessageBox::Show("leave control error");
}
if (dynamic_cast<ConstraintException^>(anError->Exception) != nullptr)
{
DataGridView^ view = (DataGridView^)sender;
view->Rows[anError->RowIndex]->ErrorText = "an error";
view->Rows[anError->RowIndex]->Cells[anError->ColumnIndex]->ErrorText = "an error";
anError->ThrowException = false;
}
}
#pragma endregion
private:
void DataGridView1_CellContentClick(Object^ /*sender*/, DataGridViewCellEventArgs^ e)
{
if (IsANonHeaderLinkCell(e))
{
MoveToLinked(e);
}
else if (IsANonHeaderButtonCell(e))
{
PopulateSales(e);
}
}
private:
void MoveToLinked(DataGridViewCellEventArgs^ e)
{
String^ employeeId;
Object^ value = DataGridView1->Rows[e->RowIndex]->Cells[e->ColumnIndex]->Value;
if (dynamic_cast<DBNull^>(value) != nullptr) { return; }
employeeId = value->ToString();
DataGridViewCell^ boss = RetrieveSuperiorsLastNameCell(employeeId);
if (boss != nullptr)
{
DataGridView1->CurrentCell = boss;
}
}
private:
bool IsANonHeaderLinkCell(DataGridViewCellEventArgs^ cellEvent)
{
if (dynamic_cast<DataGridViewLinkColumn^>(DataGridView1->Columns[cellEvent->ColumnIndex]) != nullptr
&&
cellEvent->RowIndex != -1)
{ return true; }
else { return false; }
}
private:
bool IsANonHeaderButtonCell(DataGridViewCellEventArgs^ cellEvent)
{
if (dynamic_cast<DataGridViewButtonColumn^>(DataGridView1->Columns[cellEvent->ColumnIndex]) != nullptr
&&
cellEvent->RowIndex != -1)
{ return true; }
else { return (false); }
}
private:
DataGridViewCell^ RetrieveSuperiorsLastNameCell(String^ employeeId)
{
for each (DataGridViewRow^ row in DataGridView1->Rows)
{
if (row->IsNewRow) { return nullptr; }
if (row->Cells[ColumnName::EmployeeID.ToString()]->Value->ToString()->Equals(employeeId))
{
return row->Cells[ColumnName::LastName.ToString()];
}
}
return nullptr;
}
#pragma region "checkbox state"
private:
void DataGridView1_CellValuePushed(Object^ sender,
DataGridViewCellValueEventArgs^ e)
{
if (IsCheckBoxColumn(e->ColumnIndex))
{
String^ employeeId = GetKey(e);
if (!inOffice->ContainsKey(employeeId))
{
inOffice->Add(employeeId, (Boolean)e->Value);
}
else
{
inOffice[employeeId] = (Boolean)e->Value;
}
}
}
private:
String^ GetKey(DataGridViewCellValueEventArgs^ cell)
{
return DataGridView1->Rows[cell->RowIndex]->
Cells[ColumnName::EmployeeID.ToString()]->Value->ToString();
}
private:
void DataGridView1_CellValueNeeded(Object^ sender,
DataGridViewCellValueEventArgs^ e)
{
if (IsCheckBoxColumn(e->ColumnIndex))
{
String^ employeeId = GetKey(e);
if (!inOffice->ContainsKey(employeeId))
{
bool defaultValue = false;
inOffice->Add(employeeId, defaultValue);
}
e->Value = inOffice[employeeId];
}
}
private:
bool IsCheckBoxColumn(int columnIndex)
{
DataGridViewColumn^ outOfOfficeColumn =
DataGridView1->Columns[ColumnName::OutOfOffice.ToString()];
return (DataGridView1->Columns[columnIndex] == outOfOfficeColumn);
}
#pragma endregion
};
int main()
{
Employees::Main();
}
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Drawing;
public class Employees : Form
{
private DataGridView DataGridView1 = new DataGridView();
private DataGridView DataGridView2 = new DataGridView();
[STAThread]
public static void Main()
{
try
{
Application.EnableVisualStyles();
Application.Run(new Employees());
}
catch (Exception e)
{
MessageBox.Show(e.Message + e.StackTrace);
}
}
public Employees()
{
this.Load += new EventHandler(Form1_Load);
}
private void Form1_Load(System.Object sender, System.EventArgs e)
{
try
{
SetUpForm();
SetUpDataGridView1();
SetUpDataGridView2();
}
catch (SqlException)
{
MessageBox.Show("The connection string <"
+ connectionString
+ "> failed to connect. Modify it "
+ "to connect to a Northwind database accessible to "
+ "your system.",
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Application.Exit();
}
}
private void SetUpForm()
{
Size = new Size(800, 600);
FlowLayoutPanel flowLayout = new FlowLayoutPanel();
flowLayout.FlowDirection = FlowDirection.TopDown;
flowLayout.Dock = DockStyle.Fill;
Controls.Add(flowLayout);
Text = "DataGridView columns demo";
flowLayout.Controls.Add(DataGridView1);
flowLayout.Controls.Add(DataGridView2);
}
private void SetUpDataGridView2()
{
DataGridView2.Dock = DockStyle.Bottom;
DataGridView2.TopLeftHeaderCell.Value = "Sales Details";
DataGridView2.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
}
private void SetUpDataGridView1()
{
DataGridView1.DataError += new
DataGridViewDataErrorEventHandler(DataGridView1_DataError);
DataGridView1.CellContentClick += new
DataGridViewCellEventHandler(DataGridView1_CellContentClick);
DataGridView1.CellValuePushed += new
DataGridViewCellValueEventHandler(DataGridView1_CellValuePushed);
DataGridView1.CellValueNeeded += new
DataGridViewCellValueEventHandler(DataGridView1_CellValueNeeded);
// Virtual mode is turned on so that the
// unbound DataGridViewCheckBoxColumn will
// keep its state when the bound columns are
// sorted.
DataGridView1.VirtualMode = true;
DataGridView1.AutoSize = true;
DataGridView1.DataSource = Populate("SELECT * FROM Employees");
DataGridView1.TopLeftHeaderCell.Value = "Employees";
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView1.AllowUserToAddRows = false;
DataGridView1.AllowUserToDeleteRows = false;
// The below autogenerated column is removed so
// a DataGridViewComboboxColumn could be used instead.
DataGridView1.Columns.Remove(ColumnName.TitleOfCourtesy.ToString());
DataGridView1.Columns.Remove(ColumnName.ReportsTo.ToString());
AddLinkColumn();
AddComboBoxColumns();
AddButtonColumn();
AddOutOfOfficeColumn();
}
private void AddComboBoxColumns()
{
DataGridViewComboBoxColumn comboboxColumn;
comboboxColumn = CreateComboBoxColumn();
SetAlternateChoicesUsingDataSource(comboboxColumn);
comboboxColumn.HeaderText = "TitleOfCourtesy (via DataSource property)";
DataGridView1.Columns.Insert(0, comboboxColumn);
comboboxColumn = CreateComboBoxColumn();
SetAlternateChoicesUsingItems(comboboxColumn);
comboboxColumn.HeaderText = "TitleOfCourtesy (via Items property)";
// Tack this example column onto the end.
DataGridView1.Columns.Add(comboboxColumn);
}
private void AddLinkColumn()
{
DataGridViewLinkColumn links = new DataGridViewLinkColumn();
links.UseColumnTextForLinkValue = true;
links.HeaderText = ColumnName.ReportsTo.ToString();
links.DataPropertyName = ColumnName.ReportsTo.ToString();
links.ActiveLinkColor = Color.White;
links.LinkBehavior = LinkBehavior.SystemDefault;
links.LinkColor = Color.Blue;
links.TrackVisitedState = true;
links.VisitedLinkColor = Color.YellowGreen;
DataGridView1.Columns.Add(links);
}
private static void SetAlternateChoicesUsingItems(
DataGridViewComboBoxColumn comboboxColumn)
{
comboboxColumn.Items.AddRange("Mr.", "Ms.", "Mrs.", "Dr.");
}
private DataGridViewComboBoxColumn CreateComboBoxColumn()
{
DataGridViewComboBoxColumn column =
new DataGridViewComboBoxColumn();
{
column.DataPropertyName = ColumnName.TitleOfCourtesy.ToString();
column.HeaderText = ColumnName.TitleOfCourtesy.ToString();
column.DropDownWidth = 160;
column.Width = 90;
column.MaxDropDownItems = 3;
column.FlatStyle = FlatStyle.Flat;
}
return column;
}
private void SetAlternateChoicesUsingDataSource(DataGridViewComboBoxColumn comboboxColumn)
{
{
comboboxColumn.DataSource = RetrieveAlternativeTitles();
comboboxColumn.ValueMember = ColumnName.TitleOfCourtesy.ToString();
comboboxColumn.DisplayMember = comboboxColumn.ValueMember;
}
}
private DataTable RetrieveAlternativeTitles()
{
return Populate("SELECT distinct TitleOfCourtesy FROM Employees");
}
string connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";
private DataTable Populate(string sqlCommand)
{
SqlConnection northwindConnection = new SqlConnection(connectionString);
northwindConnection.Open();
SqlCommand command = new SqlCommand(sqlCommand, northwindConnection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
// Using an enum provides some abstraction between column index
// and column name along with compile time checking, and gives
// a handy place to store the column names.
enum ColumnName
{
EmployeeId,
LastName,
FirstName,
Title,
TitleOfCourtesy,
BirthDate,
HireDate,
Address,
City,
Region,
PostalCode,
Country,
HomePhone,
Extension,
Photo,
Notes,
ReportsTo,
PhotoPath,
OutOfOffice
};
private void AddButtonColumn()
{
DataGridViewButtonColumn buttons = new DataGridViewButtonColumn();
{
buttons.HeaderText = "Sales";
buttons.Text = "Sales";
buttons.UseColumnTextForButtonValue = true;
buttons.AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
buttons.FlatStyle = FlatStyle.Standard;
buttons.CellTemplate.Style.BackColor = Color.Honeydew;
buttons.DisplayIndex = 0;
}
DataGridView1.Columns.Add(buttons);
}
private void AddOutOfOfficeColumn()
{
DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
{
column.HeaderText = ColumnName.OutOfOffice.ToString();
column.Name = ColumnName.OutOfOffice.ToString();
column.AutoSizeMode =
DataGridViewAutoSizeColumnMode.DisplayedCells;
column.FlatStyle = FlatStyle.Standard;
column.ThreeState = true;
column.CellTemplate = new DataGridViewCheckBoxCell();
column.CellTemplate.Style.BackColor = Color.Beige;
}
DataGridView1.Columns.Insert(0, column);
}
private void PopulateSales(DataGridViewCellEventArgs buttonClick)
{
string employeeId = DataGridView1.Rows[buttonClick.RowIndex]
.Cells[ColumnName.EmployeeId.ToString()].Value.ToString();
DataGridView2.DataSource = Populate("SELECT * FROM Orders WHERE EmployeeId = " + employeeId);
}
#region "SQL Error handling"
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
MessageBox.Show("Error happened " + anError.Context.ToString());
if (anError.Context == DataGridViewDataErrorContexts.Commit)
{
MessageBox.Show("Commit error");
}
if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
{
MessageBox.Show("Cell change");
}
if (anError.Context == DataGridViewDataErrorContexts.Parsing)
{
MessageBox.Show("parsing error");
}
if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
{
MessageBox.Show("leave control error");
}
if ((anError.Exception) is ConstraintException)
{
DataGridView view = (DataGridView)sender;
view.Rows[anError.RowIndex].ErrorText = "an error";
view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
#endregion
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (IsANonHeaderLinkCell(e))
{
MoveToLinked(e);
}
else if (IsANonHeaderButtonCell(e))
{
PopulateSales(e);
}
}
private void MoveToLinked(DataGridViewCellEventArgs e)
{
string employeeId;
object value = DataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (value is DBNull) { return; }
employeeId = value.ToString();
DataGridViewCell boss = RetrieveSuperiorsLastNameCell(employeeId);
if (boss != null)
{
DataGridView1.CurrentCell = boss;
}
}
private bool IsANonHeaderLinkCell(DataGridViewCellEventArgs cellEvent)
{
if (DataGridView1.Columns[cellEvent.ColumnIndex] is
DataGridViewLinkColumn &&
cellEvent.RowIndex != -1)
{ return true; }
else { return false; }
}
private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
{
if (DataGridView1.Columns[cellEvent.ColumnIndex] is
DataGridViewButtonColumn &&
cellEvent.RowIndex != -1)
{ return true; }
else { return (false); }
}
private DataGridViewCell RetrieveSuperiorsLastNameCell(string employeeId)
{
foreach (DataGridViewRow row in DataGridView1.Rows)
{
if (row.IsNewRow) { return null; }
if (row.Cells[ColumnName.EmployeeId.ToString()].Value.ToString().Equals(employeeId))
{
return row.Cells[ColumnName.LastName.ToString()];
}
}
return null;
}
#region "checkbox state"
Dictionary<string, bool> inOffice = new Dictionary<string, bool>();
private void DataGridView1_CellValuePushed(object sender,
DataGridViewCellValueEventArgs e)
{
if (IsCheckBoxColumn(e.ColumnIndex))
{
string employeeId = GetKey(e);
if (!inOffice.ContainsKey(employeeId))
{
inOffice.Add(employeeId, (Boolean)e.Value);
}
else
{
inOffice[employeeId] = (Boolean)e.Value;
}
}
}
private string GetKey(DataGridViewCellValueEventArgs cell)
{
return DataGridView1.Rows[cell.RowIndex].
Cells[ColumnName.EmployeeId.ToString()].Value.ToString();
}
private void DataGridView1_CellValueNeeded(object sender,
DataGridViewCellValueEventArgs e)
{
if (IsCheckBoxColumn(e.ColumnIndex))
{
string employeeId = GetKey(e);
if (!inOffice.ContainsKey(employeeId))
{
bool defaultValue = false;
inOffice.Add(employeeId, defaultValue);
}
e.Value = inOffice[employeeId];
}
}
private bool IsCheckBoxColumn(int columnIndex)
{
DataGridViewColumn outOfOfficeColumn =
DataGridView1.Columns[ColumnName.OutOfOffice.ToString()];
return (DataGridView1.Columns[columnIndex] == outOfOfficeColumn);
}
#endregion
}
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.Drawing
Public Class Employees
Inherits System.Windows.Forms.Form
Private WithEvents DataGridView1 As New DataGridView
Private WithEvents DataGridView2 As New DataGridView
<STAThreadAttribute()> _
Public Shared Sub Main()
Try
Application.EnableVisualStyles()
Application.Run(New Employees())
Catch e As Exception
MessageBox.Show(e.Message & e.StackTrace)
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Try
SetUpForm()
SetUpDataGridView1()
SetUpDataGridView2()
Catch ex As SqlException
MessageBox.Show("The connection string <" _
& connectionString _
& "> failed to connect. Modify it to connect to " _
& "a Northwind database accessible to your system.", _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Application.Exit()
End Try
End Sub
Private Sub SetUpForm()
Size = New Size(800, 600)
Dim flowLayout As New FlowLayoutPanel()
flowLayout.FlowDirection = FlowDirection.TopDown
flowLayout.Dock = DockStyle.Fill
Controls.Add(flowLayout)
Text = "DataGridView columns demo"
flowLayout.Controls.Add(DataGridView1)
flowLayout.Controls.Add(DataGridView2)
End Sub
Private Sub SetUpDataGridView2()
DataGridView2.Dock = DockStyle.Bottom
DataGridView2.TopLeftHeaderCell.Value = "Sales Details"
DataGridView2.RowHeadersWidthSizeMode = _
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
End Sub
Private Sub SetUpDataGridView1()
' Virtual mode is turned on so that the
' unbound DataGridViewCheckBoxColumn will
' keep its state when the bound columns are
' sorted.
DataGridView1.VirtualMode = True
DataGridView1.AutoSize = True
DataGridView1.DataSource = _
Populate("SELECT * FROM Employees")
DataGridView1.TopLeftHeaderCell.Value = "Employees"
DataGridView1.RowHeadersWidthSizeMode = _
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
DataGridView1.ColumnHeadersHeightSizeMode = _
DataGridViewColumnHeadersHeightSizeMode.AutoSize
DataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.AllCells
DataGridView1.AllowUserToAddRows = False
DataGridView1.AllowUserToDeleteRows = False
' The below autogenerated column is removed so
' a DataGridViewComboboxColumn could be used instead.
DataGridView1.Columns.Remove( _
ColumnName.TitleOfCourtesy.ToString())
DataGridView1.Columns.Remove(ColumnName.ReportsTo.ToString())
AddLinkColumn()
AddComboBoxColumns()
AddButtonColumn()
AddOutOfOfficeColumn()
End Sub
Private Sub AddComboBoxColumns()
Dim comboboxColumn As DataGridViewComboBoxColumn
comboboxColumn = CreateComboBoxColumn()
SetAlternateChoicesUsingDataSource(comboboxColumn)
comboboxColumn.HeaderText = _
"TitleOfCourtesy (via DataSource property)"
DataGridView1.Columns.Insert(0, comboboxColumn)
comboboxColumn = CreateComboBoxColumn()
SetAlternateChoicesUsingItems(comboboxColumn)
comboboxColumn.HeaderText = _
"TitleOfCourtesy (via Items property)"
' Tack this example column onto the end.
DataGridView1.Columns.Add(comboboxColumn)
End Sub
Private Sub AddLinkColumn()
Dim links As New DataGridViewLinkColumn()
With links
.UseColumnTextForLinkValue = True
.HeaderText = ColumnName.ReportsTo.ToString()
.DataPropertyName = ColumnName.ReportsTo.ToString()
.ActiveLinkColor = Color.White
.LinkBehavior = LinkBehavior.SystemDefault
.LinkColor = Color.Blue
.TrackVisitedState = True
.VisitedLinkColor = Color.YellowGreen
End With
DataGridView1.Columns.Add(links)
End Sub
Private Shared Sub SetAlternateChoicesUsingItems( _
ByVal comboboxColumn As DataGridViewComboBoxColumn)
comboboxColumn.Items.AddRange("Mr.", "Ms.", "Mrs.", "Dr.")
End Sub
Private Function CreateComboBoxColumn() _
As DataGridViewComboBoxColumn
Dim column As New DataGridViewComboBoxColumn()
With column
.DataPropertyName = ColumnName.TitleOfCourtesy.ToString()
.HeaderText = ColumnName.TitleOfCourtesy.ToString()
.DropDownWidth = 160
.Width = 90
.MaxDropDownItems = 3
.FlatStyle = FlatStyle.Flat
End With
Return column
End Function
Private Sub SetAlternateChoicesUsingDataSource( _
ByVal comboboxColumn As DataGridViewComboBoxColumn)
With comboboxColumn
.DataSource = RetrieveAlternativeTitles()
.ValueMember = ColumnName.TitleOfCourtesy.ToString()
.DisplayMember = .ValueMember
End With
End Sub
Private Function RetrieveAlternativeTitles() As DataTable
Return Populate( _
"SELECT distinct TitleOfCourtesy FROM Employees")
End Function
Private connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" _
& "Initial Catalog=Northwind;Data Source=localhost"
Private Function Populate(ByVal sqlCommand As String) As DataTable
Dim northwindConnection As New SqlConnection(connectionString)
northwindConnection.Open()
Dim command As New SqlCommand(sqlCommand, _
northwindConnection)
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = command
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
adapter.Fill(table)
Return table
End Function
' Using an enum provides some abstraction between column index
' and column name along with compile time checking, and gives
' a handy place to store the column names.
Enum ColumnName
EmployeeId
LastName
FirstName
Title
TitleOfCourtesy
BirthDate
HireDate
Address
City
Region
PostalCode
Country
HomePhone
Extension
Photo
Notes
ReportsTo
PhotoPath
OutOfOffice
End Enum
Private Sub AddButtonColumn()
Dim buttons As New DataGridViewButtonColumn()
With buttons
.HeaderText = "Sales"
.Text = "Sales"
.UseColumnTextForButtonValue = True
.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
.FlatStyle = FlatStyle.Standard
.CellTemplate.Style.BackColor = Color.Honeydew
.DisplayIndex = 0
End With
DataGridView1.Columns.Add(buttons)
End Sub
Private Sub AddOutOfOfficeColumn()
Dim column As New DataGridViewCheckBoxColumn()
With column
.HeaderText = ColumnName.OutOfOffice.ToString()
.Name = ColumnName.OutOfOffice.ToString()
.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
.FlatStyle = FlatStyle.Standard
.CellTemplate = New DataGridViewCheckBoxCell()
.CellTemplate.Style.BackColor = Color.Beige
End With
DataGridView1.Columns.Insert(0, column)
End Sub
Private Sub PopulateSales( _
ByVal buttonClick As DataGridViewCellEventArgs)
Dim employeeId As String = _
DataGridView1.Rows(buttonClick.RowIndex). _
Cells(ColumnName.EmployeeId.ToString()).Value().ToString()
DataGridView2.DataSource = Populate( _
"SELECT * FROM Orders WHERE EmployeeId = " & employeeId)
End Sub
#Region "SQL Error handling"
Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
MessageBox.Show("Error happened " _
& e.Context.ToString())
If (e.Context = DataGridViewDataErrorContexts.Commit) _
Then
MessageBox.Show("Commit error")
End If
If (e.Context = DataGridViewDataErrorContexts _
.CurrentCellChange) Then
MessageBox.Show("Cell change")
End If
If (e.Context = DataGridViewDataErrorContexts.Parsing) _
Then
MessageBox.Show("parsing error")
End If
If (e.Context = _
DataGridViewDataErrorContexts.LeaveControl) Then
MessageBox.Show("leave control error")
End If
If (TypeOf (e.Exception) Is ConstraintException) Then
Dim view As DataGridView = CType(sender, DataGridView)
view.Rows(e.RowIndex).ErrorText = "an error"
view.Rows(e.RowIndex).Cells(e.ColumnIndex) _
.ErrorText = "an error"
e.ThrowException = False
End If
End Sub
#End Region
Private Sub DataGridView1_CellContentClick(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellContentClick
If IsANonHeaderLinkCell(e) Then
MoveToLinked(e)
ElseIf IsANonHeaderButtonCell(e) Then
PopulateSales(e)
End If
End Sub
Private Sub MoveToLinked(ByVal e As DataGridViewCellEventArgs)
Dim employeeId As String
Dim value As Object = DataGridView1.Rows(e.RowIndex). _
Cells(e.ColumnIndex).Value
If value.GetType Is GetType(DBNull) Then Return
employeeId = CType(value, String)
Dim boss As DataGridViewCell = _
RetrieveSuperiorsLastNameCell(employeeId)
If boss IsNot Nothing Then
DataGridView1.CurrentCell = boss
End If
End Sub
Private Function IsANonHeaderLinkCell(ByVal cellEvent As _
DataGridViewCellEventArgs) As Boolean
If TypeOf DataGridView1.Columns(cellEvent.ColumnIndex) _
Is DataGridViewLinkColumn _
AndAlso Not cellEvent.RowIndex = -1 Then _
Return True Else Return False
End Function
Private Function IsANonHeaderButtonCell(ByVal cellEvent As _
DataGridViewCellEventArgs) As Boolean
If TypeOf DataGridView1.Columns(cellEvent.ColumnIndex) _
Is DataGridViewButtonColumn _
AndAlso Not cellEvent.RowIndex = -1 Then _
Return True Else Return (False)
End Function
Private Function RetrieveSuperiorsLastNameCell( _
ByVal employeeId As String) As DataGridViewCell
For Each row As DataGridViewRow In DataGridView1.Rows
If row.IsNewRow Then Return Nothing
If row.Cells(ColumnName.EmployeeId.ToString()). _
Value.ToString().Equals(employeeId) Then
Return row.Cells(ColumnName.LastName.ToString())
End If
Next
Return Nothing
End Function
#Region "checkbox state"
Dim inOffice As New Dictionary(Of String, Boolean)
Private Sub DataGridView1_CellValuePushed(ByVal sender As Object, _
ByVal e As DataGridViewCellValueEventArgs) _
Handles DataGridView1.CellValuePushed
If IsCheckBoxColumn(e.ColumnIndex) Then
Dim employeeId As String = GetKey(e)
If Not inOffice.ContainsKey(employeeId) Then
inOffice.Add(employeeId, CType(e.Value, Boolean))
Else
inOffice.Item(employeeId) = CType(e.Value, Boolean)
End If
End If
End Sub
Private Function GetKey(ByVal cell As DataGridViewCellValueEventArgs) As String
Return DataGridView1.Rows(cell.RowIndex).Cells( _
ColumnName.EmployeeId.ToString()).Value().ToString()
End Function
Private Sub DataGridView1_CellValueNeeded(ByVal sender As Object, _
ByVal e As DataGridViewCellValueEventArgs) _
Handles DataGridView1.CellValueNeeded
If IsCheckBoxColumn(e.ColumnIndex) Then
Dim employeeId As String = GetKey(e)
If Not inOffice.ContainsKey(employeeId) Then
Dim defaultValue As Boolean = False
inOffice.Add(employeeId, defaultValue)
End If
e.Value = inOffice.Item(employeeId)
End If
End Sub
Private Function IsCheckBoxColumn(ByVal columnIndex As Integer) As Boolean
Dim outOfOfficeColumn As DataGridViewColumn = _
DataGridView1.Columns(ColumnName.OutOfOffice.ToString())
Return (DataGridView1.Columns(columnIndex) Is outOfOfficeColumn)
End Function
#End Region
End Class
Remarks
The DataGridViewComboBoxColumn class is a specialized type of DataGridViewColumn used to logically host cells that enable users to select values from a list of choices. A DataGridViewComboBoxColumn has an associated DataGridViewComboBoxCell in every DataGridViewRow that intersects it.
You can populate the cells manually by setting their Value properties. Alternatively, you can bind the column to the data source indicated by the DataGridView.DataSource property. If the DataGridView is bound to a database table, set the column DataPropertyName property to the name of a column in the table. If the DataGridView is bound to a collection of objects, set the DataPropertyName property to the name of an object property.
You can populate the column drop-down list manually by adding values to the Items collection. Alternatively, you can bind the drop-down list to its own data source by setting the column DataSource property. If the values are objects in a collection or records in a database table, you must also set the DisplayMember and ValueMember properties. The DisplayMember property indicates which object property or database column provides the values that are displayed in the drop-down list. The ValueMember property indicates which object property or database column is used to set the cell Value property.
One typical scenario is to bind the DataGridView control to a parent database table and bind the drop-down list to a related child table. For example, you might bind the DataGridView control to an Orders
table that contains a ProductID
column and set the column DataSource property to a Products
table that contains ProductID
and ProductName
columns. In this case, you would set the column DataPropertyName property to "ProductID" to populate its cell values from the Orders.ProductID
column. However, to display the actual product names in the cells and the drop-down list, you would map these values to the Products
table by setting the ValueMember property to "ProductID" and the DisplayMember property to "ProductName".
The drop-down list values (or the values indicated by the ValueMember property) must include the actual cell values or the DataGridView control will throw an exception.
Setting the column DataSource, DisplayMember, and ValueMember properties automatically sets the corresponding properties of all cells in the column including the CellTemplate. To override these property values for specific cells, set the column property first, and then set the cell properties.
Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.
The default sort mode for this column type is NotSortable.
Notes to Inheritors
When you derive from DataGridViewComboBoxColumn and add new properties to the derived class, be sure to override the Clone() method to copy the new properties during cloning operations. You should also call the base class's Clone() method so that the properties of the base class are copied to the new cell.
Constructors
DataGridViewComboBoxColumn() |
Initializes a new instance of the DataGridViewTextBoxColumn class to the default state. |
Properties
AutoComplete |
Gets or sets a value indicating whether cells in the column will match the characters being entered in the cell with one from the possible selections. |
AutoSizeMode |
Gets or sets the mode by which the column automatically adjusts its width. (Inherited from DataGridViewColumn) |
CellTemplate |
Gets or sets the template used to create cells. |
CellType |
Gets the run-time type of the cell template. (Inherited from DataGridViewColumn) |
ContextMenuStrip |
Gets or sets the shortcut menu for the column. (Inherited from DataGridViewColumn) |
DataGridView |
Gets the DataGridView control associated with this element. (Inherited from DataGridViewElement) |
DataPropertyName |
Gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound. (Inherited from DataGridViewColumn) |
DataSource |
Gets or sets the data source that populates the selections for the combo boxes. |
DefaultCellStyle |
Gets or sets the column's default cell style. (Inherited from DataGridViewColumn) |
DefaultHeaderCellType |
Gets or sets the run-time type of the default header cell. (Inherited from DataGridViewBand) |
Displayed |
Gets a value indicating whether the band is currently displayed onscreen. (Inherited from DataGridViewBand) |
DisplayIndex |
Gets or sets the display order of the column relative to the currently displayed columns. (Inherited from DataGridViewColumn) |
DisplayMember |
Gets or sets a string that specifies the property or column from which to retrieve strings for display in the combo boxes. |
DisplayStyle |
Gets or sets a value that determines how the combo box is displayed when not editing. |
DisplayStyleForCurrentCellOnly |
Gets or sets a value indicating whether the DisplayStyle property value applies only to the current cell in the DataGridView control when the current cell is in this column. |
DividerWidth |
Gets or sets the width, in pixels, of the column divider. (Inherited from DataGridViewColumn) |
DropDownWidth |
Gets or sets the width of the drop-down lists of the combo boxes. |
FillWeight |
Gets or sets a value that represents the width of the column when it is in fill mode relative to the widths of other fill-mode columns in the control. (Inherited from DataGridViewColumn) |
FlatStyle |
Gets or sets the flat style appearance of the column's cells. |
Frozen |
Gets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally. (Inherited from DataGridViewColumn) |
HasDefaultCellStyle |
Gets a value indicating whether the DefaultCellStyle property has been set. (Inherited from DataGridViewBand) |
HeaderCell |
Gets or sets the DataGridViewColumnHeaderCell that represents the column header. (Inherited from DataGridViewColumn) |
HeaderCellCore |
Gets or sets the header cell of the DataGridViewBand. (Inherited from DataGridViewBand) |
HeaderText |
Gets or sets the caption text on the column's header cell. (Inherited from DataGridViewColumn) |
Index |
Gets the relative position of the band within the DataGridView control. (Inherited from DataGridViewBand) |
InheritedAutoSizeMode |
Gets the sizing mode in effect for the column. (Inherited from DataGridViewColumn) |
InheritedStyle |
Gets the cell style currently applied to the column. (Inherited from DataGridViewColumn) |
IsDataBound |
Gets a value indicating whether the column is bound to a data source. (Inherited from DataGridViewColumn) |
IsRow |
Gets a value indicating whether the band represents a row. (Inherited from DataGridViewBand) |
Items |
Gets the collection of objects used as selections in the combo boxes. |
MaxDropDownItems |
Gets or sets the maximum number of items in the drop-down list of the cells in the column. |
MinimumWidth |
Gets or sets the minimum width, in pixels, of the column. (Inherited from DataGridViewColumn) |
Name |
Gets or sets the name of the column. (Inherited from DataGridViewColumn) |
ReadOnly |
Gets or sets a value indicating whether the user can edit the column's cells. (Inherited from DataGridViewColumn) |
Resizable |
Gets or sets a value indicating whether the column is resizable. (Inherited from DataGridViewColumn) |
Selected |
Gets or sets a value indicating whether the band is in a selected user interface (UI) state. (Inherited from DataGridViewBand) |
Site |
Gets or sets the site of the column. (Inherited from DataGridViewColumn) |
Sorted |
Gets or sets a value indicating whether the items in the combo box are sorted. |
SortMode |
Gets or sets the sort mode for the column. (Inherited from DataGridViewColumn) |
State |
Gets the user interface (UI) state of the element. (Inherited from DataGridViewElement) |
Tag |
Gets or sets the object that contains data to associate with the band. (Inherited from DataGridViewBand) |
ToolTipText |
Gets or sets the text used for ToolTips. (Inherited from DataGridViewColumn) |
ValueMember |
Gets or sets a string that specifies the property or column from which to get values that correspond to the selections in the drop-down list. |
ValueType |
Gets or sets the data type of the values in the column's cells. (Inherited from DataGridViewColumn) |
Visible |
Gets or sets a value indicating whether the column is visible. (Inherited from DataGridViewColumn) |
Width |
Gets or sets the current width of the column. (Inherited from DataGridViewColumn) |
Methods
Clone() |
Creates an exact copy of this column. |
Dispose() |
Releases all resources used by the DataGridViewBand. (Inherited from DataGridViewBand) |
Dispose(Boolean) |
Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources. (Inherited from DataGridViewColumn) |
Equals(Object) |
Determines whether the specified object is equal to the current object. (Inherited from Object) |
GetHashCode() |
Serves as the default hash function. (Inherited from Object) |
GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean) |
Calculates the ideal width of the column based on the specified criteria. (Inherited from DataGridViewColumn) |
GetType() |
Gets the Type of the current instance. (Inherited from Object) |
MemberwiseClone() |
Creates a shallow copy of the current Object. (Inherited from Object) |
OnDataGridViewChanged() |
Called when the band is associated with a different DataGridView. (Inherited from DataGridViewBand) |
RaiseCellClick(DataGridViewCellEventArgs) |
Raises the CellClick event. (Inherited from DataGridViewElement) |
RaiseCellContentClick(DataGridViewCellEventArgs) |
Raises the CellContentClick event. (Inherited from DataGridViewElement) |
RaiseCellContentDoubleClick(DataGridViewCellEventArgs) |
Raises the CellContentDoubleClick event. (Inherited from DataGridViewElement) |
RaiseCellValueChanged(DataGridViewCellEventArgs) |
Raises the CellValueChanged event. (Inherited from DataGridViewElement) |
RaiseDataError(DataGridViewDataErrorEventArgs) |
Raises the DataError event. (Inherited from DataGridViewElement) |
RaiseMouseWheel(MouseEventArgs) |
Raises the MouseWheel event. (Inherited from DataGridViewElement) |
ToString() |
Gets a string that describes the column. |
Events
Disposed |
Occurs when the DataGridViewColumn is disposed. (Inherited from DataGridViewColumn) |