DataGridViewComboBoxColumn 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
代表 DataGridViewComboBoxCell 物件的資料行。
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
- 繼承
- 屬性
範例
下列程式碼範例示範如何使用 DataGridViewComboBoxColumn 來協助將資料輸入資料行 TitleOfCourtesy
。
#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
備註
類別 DataGridViewComboBoxColumn 是特製化的 類型, DataGridViewColumn 可用來以邏輯方式裝載儲存格,讓使用者從挑選清單中選取值。 DataGridViewComboBoxColumn在與它交集的每個 DataGridViewRow 中都有相關聯的 DataGridViewComboBoxCell 。
您可以藉由設定儲存格的屬性來手動填入資料 Value 格。 或者,您可以將資料行系結至 屬性所指示的 DataGridView.DataSource 資料來源。 DataGridView如果 系結至資料庫資料表,請將資料 DataPropertyName 行屬性設定為數據表中資料行的名稱。 DataGridView如果 系結至 物件的集合,請將 DataPropertyName 屬性設定為物件屬性的名稱。
您可以將值新增至 Items 集合,以手動填入資料行下拉式清單。 或者,您可以藉由設定資料行 DataSource 屬性,將下拉式清單系結至自己的資料來源。 如果值是集合中的物件或資料庫資料表中的記錄,您也必須設定 DisplayMember 和 ValueMember 屬性。 屬性 DisplayMember 會指出哪些物件屬性或資料庫資料行提供下拉式清單中顯示的值。 屬性 ValueMember 會指出使用哪一個物件屬性或資料庫資料行來設定儲存格 Value 屬性。
其中一個典型的案例是將 DataGridView 控制項系結至父資料庫資料表,並將下拉式清單系結至相關的子資料工作表。 例如,您可以將 控制項系結至包含資料行的資料表,並將資料行 DataSource 屬性設定為 Products
包含 和 ProductName
資料行的 ProductID
資料表。 ProductID
Orders
DataGridView 在此情況下,您會將資料行 DataPropertyName 屬性設定為 「ProductID」,以從 Orders.ProductID
資料行填入其儲存格值。 不過,若要在儲存格和下拉式清單中顯示實際產品名稱,您可以將屬性設定為 「ProductID」 並將 屬性設定 ValueMember 為 「ProductName」 DisplayMember ,將這些值對應至 Products
資料表。
下拉式清單值 (或屬性所指出 ValueMember 的值) 必須包含實際的儲存格值,否則 DataGridView 控制項會擲回例外狀況。
設定資料行 DataSource 、 DisplayMember 和 ValueMember 屬性會自動設定資料行中所有儲存格的對應屬性,包括 CellTemplate 。 若要覆寫特定儲存格的這些屬性值,請先設定資料行屬性,然後設定儲存格屬性。
ComboBox不同于 控制項, DataGridViewComboBoxCell 沒有 SelectedIndex 和 SelectedValue 屬性。 相反地,從下拉式清單中選取值會設定儲存格 Value 屬性。
此資料行類型的預設排序模式為 NotSortable 。
給繼承者的注意事項
當您衍生自 DataGridViewComboBoxColumn 並將新屬性新增至衍生類別時,請務必覆寫 Clone() 方法,以在複製作業期間複製新屬性。 您也應該呼叫基類的 Clone() 方法,以便基類的屬性複製到新的儲存格。
建構函式
DataGridViewComboBoxColumn() |
初始化 DataGridViewTextBoxColumn 類別的新執行個體為預設狀態。 |
屬性
AutoComplete |
取得或設定值,指出資料行中的儲存格是否會符合輸入具有一個可能選項的儲存格中的字元。 |
AutoSizeMode |
取得或設定資料行自動調整其寬度所根據的模式。 (繼承來源 DataGridViewColumn) |
CellTemplate |
取得或設定用來建立儲存格的樣板。 |
CellType |
取得儲存格樣板的執行階段類型。 (繼承來源 DataGridViewColumn) |
ContextMenuStrip |
取得或設定資料行的捷徑功能表。 (繼承來源 DataGridViewColumn) |
DataGridView |
取得與這個項目有關聯的 DataGridView 控制項。 (繼承來源 DataGridViewElement) |
DataPropertyName |
取得或設定 DataGridViewColumn 所繫結的資料來源屬性或資料庫資料行的名稱。 (繼承來源 DataGridViewColumn) |
DataSource |
取得或設定可填入下拉式方塊選擇的資料來源。 |
DefaultCellStyle |
取得或設定資料行的預設儲存格樣式。 (繼承來源 DataGridViewColumn) |
DefaultHeaderCellType |
取得或設定預設標題儲存格的執行階段型別。 (繼承來源 DataGridViewBand) |
Displayed |
取得值,指出此群組列目前是否顯示在螢幕上。 (繼承來源 DataGridViewBand) |
DisplayIndex |
取得或設定相對於目前所顯示之資料行的資料行顯示順序。 (繼承來源 DataGridViewColumn) |
DisplayMember |
取得或設定字串,此字串指定要從中擷取字串來顯示於下拉式方塊中的屬性或資料行。 |
DisplayStyle |
取得或設定值,這個值可判斷當不進行編輯時,要如何顯示此下拉式方塊。 |
DisplayStyleForCurrentCellOnly |
取得或設定值,指出當目前的儲存格位於這個資料行時,DisplayStyle 屬性值是否僅套用至 DataGridView 控制項中目前的儲存格。 |
DividerWidth |
取得或設定資料行分割線的寬度 (以像素為單位)。 (繼承來源 DataGridViewColumn) |
DropDownWidth |
取得或設定下拉式方塊的下拉式清單的寬度。 |
FillWeight |
取得或設定值,表示處於填入模式中的資料行寬度,相對於控制項中處於填入模式的資料行寬度。 (繼承來源 DataGridViewColumn) |
FlatStyle |
取得或設定資料行的儲存格之平面樣式外觀。 |
Frozen |
取得或設定值,指出當使用者水平捲動 DataGridView 控制項時,資料行是否會跟著移動。 (繼承來源 DataGridViewColumn) |
HasDefaultCellStyle |
取得指出是否已經設定 DefaultCellStyle 屬性的值。 (繼承來源 DataGridViewBand) |
HeaderCell |
取得或設定表示資料行行首的 DataGridViewColumnHeaderCell。 (繼承來源 DataGridViewColumn) |
HeaderCellCore |
取得或設定 DataGridViewBand 的標題儲存格。 (繼承來源 DataGridViewBand) |
HeaderText |
取得或設定資料行行首儲存格上的標題文字。 (繼承來源 DataGridViewColumn) |
Index |
取得 DataGridView 控制項內群組列的相對位置。 (繼承來源 DataGridViewBand) |
InheritedAutoSizeMode |
取得資料行的作用中調整大小模式。 (繼承來源 DataGridViewColumn) |
InheritedStyle |
取得目前套用至資料行的儲存格樣式。 (繼承來源 DataGridViewColumn) |
IsDataBound |
取得值指出資料行是否繫結至資料來源。 (繼承來源 DataGridViewColumn) |
IsRow |
取得值,指出群組列是否表示資料列。 (繼承來源 DataGridViewBand) |
Items |
取得當做下拉式方塊中的選項使用的物件集合。 |
MaxDropDownItems |
取得或設定資料行中的儲存格之下拉式清單內的最大項目數。 |
MinimumWidth |
取得或設定資料行的最小寬度 (以像素為單位)。 (繼承來源 DataGridViewColumn) |
Name |
取得或設定資料行的名稱。 (繼承來源 DataGridViewColumn) |
ReadOnly |
取得或設定值,指出使用者是否可以編輯資料行的儲存格。 (繼承來源 DataGridViewColumn) |
Resizable |
取得或設定值,指出資料行是否可以重新調整大小。 (繼承來源 DataGridViewColumn) |
Selected |
取得或設定值,指出群組列是否位於已選取的使用者介面 (UI) 狀態下。 (繼承來源 DataGridViewBand) |
Site |
取得或設定資料行的站台。 (繼承來源 DataGridViewColumn) |
Sorted |
取得或設定值,指出是否排序下拉式方塊中的項目。 |
SortMode |
取得或設定資料行的排序模式。 (繼承來源 DataGridViewColumn) |
State |
取得此項目的使用者介面 (UI) 狀態。 (繼承來源 DataGridViewElement) |
Tag |
取得或設定物件,其中包含與群組列相關的資料。 (繼承來源 DataGridViewBand) |
ToolTipText |
取得或設定供工具提示使用的文字。 (繼承來源 DataGridViewColumn) |
ValueMember |
取得或設定字串,此字串指定要從中取得與下拉式清單選項對應的值之屬性或資料行。 |
ValueType |
取得或設定資枓行儲存格中的值之資料類型。 (繼承來源 DataGridViewColumn) |
Visible |
取得或設定值,這個值指出是否看得到資料行。 (繼承來源 DataGridViewColumn) |
Width |
取得或設定資料行的目前寬度。 (繼承來源 DataGridViewColumn) |
方法
事件
Disposed |
發生於處置 (Dispose) DataGridViewColumn 時。 (繼承來源 DataGridViewColumn) |