如何:访问 Windows 窗体 DataGridViewComboBoxCell 下拉列表中的对象

如何:访问 Windows 窗体 DataGridViewComboBoxCell 下拉列表中的对象
Visual Studio 2010
其他版本

* Visual Studio 2008
* .NET Framework 3.0

此内容为质量更高的人工翻译。若想同时查看此页面和原始英文页面的内容,请单击“首选项”然后选择“经典视图”作为您的查看首选项。

与 ComboBox 控件一样,DataGridViewComboBoxColumn 和 DataGridViewComboBoxCell 类型允许向其下拉列表添加任意对象。 使用此功能,可以在下拉列表中表示复杂的状态,而不必在单独集合中存储相应的对象。

与 ComboBox 控件不同,DataGridView 类型不具有用于检索当前所选对象的 SelectedItem 属性, 必须将 DataGridViewComboBoxColumn.ValueMember 或 DataGridViewComboBoxCell.ValueMember 属性设置为业务对象的属性名称。 当用户进行选择时,指示的业务对象属性将设置单元格 Value 属性。

要通过单元格值检索业务对象,ValueMember 属性必须指示一个属性,该属性返回对业务对象本身的引用。 因此,如果业务对象的类型不受您的控制,您必须通过继承来扩展该类型,从而添加此类属性。

下面的过程演示如何用业务对象填充下拉列表并通过单元格 Value 属性检索对象。


1.创建新的 DataGridViewComboBoxColumn 并填充其 Items 集合。 或者,可以将列 DataSource 属性设置为业务对象的集合。 但在这种情况下,如果没有在集合中创建相应的业务对象,就不能向下拉列表添加“未赋值”。
DataGridViewComboBoxColumn assignedToColumn =
new DataGridViewComboBoxColumn();

// Populate the combo box drop-down list with Employee objects.
foreach (Employee e in employees) assignedToColumn.Items.Add(e);

// Add "unassigned" to the drop-down list and display it for
// empty AssignedTo values or when the user presses CTRL+0.
assignedToColumn.Items.Add("unassigned");
assignedToColumn.DefaultCellStyle.NullValue = "unassigned";


2.设置 DisplayMember 和 ValueMember 属性。 DisplayMember 指示要显示在下拉列表中的业务对象的属性。 ValueMember 指示返回对业务对象的引用的属性。
assignedToColumn.DisplayMember = "Name";
assignedToColumn.ValueMember = "Self";

3.确保业务对象类型包含一个属性,该属性返回对当前实例的引用。 此属性必须以上一步中分配给 ValueMember 的值来命名。
public Employee Self
{
get { return this; }
}




检索当前所选的业务对象

*

获取单元格 Value 属性,将其强制转换为业务对象类型。
// Retrieve the Employee object from the "Assigned To" cell.
Employee assignedTo = dataGridView1.Rows[e.RowIndex]
.Cells["Assigned To"].Value as Employee;



示例:

整个示例演示了对下拉列表中业务对象的使用。 在此示例中,DataGridView 控件被绑定到 Task 对象的

集合。 每个 Task 对象都有一个 AssignedTo 属性,该属性指示当前分配给该任务的 Employee 对象。 Assigned To 列显示每个已分配员工的 Name 属性值;如果 Task.AssignedTo 属性值为 null,则显示“未赋值”。

要查看此示例的行为,请执行下列步骤:

1.

从下拉列表选择不同的值,或在组合框单元格中按 CTRL+0,从而更改 Assigned To 列中的赋值。
2.

单击 Generate Report 以显示当前赋值。 此操作演示 Assigned To 列中的更改会自动更新 tasks 集合。
3.

单击 Request Status 按钮,以便为该行调用当前 Employee 对象的 RequestStatus 方法。 此操作演示所选对象已检索成功。
using System;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;

public class Form1 : Form
{
private List employees = new List();
private List tasks = new List();
private Button reportButton = new Button();
private DataGridView dataGridView1 = new DataGridView();

[STAThread]
public static void Main()
{
Application.Run(new Form1());
}

public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
reportButton.Text = "Generate Report";
reportButton.Dock = DockStyle.Top;
reportButton.Click += new EventHandler(reportButton_Click);

Controls.Add(dataGridView1);
Controls.Add(reportButton);
Load += new EventHandler(Form1_Load);
Text = "DataGridViewComboBoxColumn Demo";
}

// Initializes the data source and populates the DataGridView control.
private void Form1_Load(object sender, EventArgs e)
{
PopulateLists();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = tasks;
AddColumns();
}

// Populates the employees and tasks lists.
private void PopulateLists()
{
employees.Add(new Employee("Harry"));
employees.Add(new Employee("Sally"));
employees.Add(new Employee("Roy"));
employees.Add(new Employee("Pris"));
tasks.Add(new Task(1, employees[1]));
tasks.Add(new Task(2));
tasks.Add(new Task(3, employees[2]));
tasks.Add(new Task(4));
}

// Configures columns for the DataGridView control.
private void AddColumns()
{
DataGridViewTextBoxColumn idColumn =
new DataGridViewTextBoxColumn();
https://www.360docs.net/doc/c63422187.html, = "Task";
idColumn.DataPropertyName = "Id";
idColumn.ReadOnly = true;

DataGridViewComboBoxColumn assignedToColumn =
new DataGridViewComboBoxColumn();

// Populate the combo box drop-down list with Employee objects.
foreach (Employee e in employees) assig

nedToColumn.Items.Add(e);

// Add "unassigned" to the drop-down list and display it for
// empty AssignedTo values or when the user presses CTRL+0.
assignedToColumn.Items.Add("unassigned");
assignedToColumn.DefaultCellStyle.NullValue = "unassigned";

https://www.360docs.net/doc/c63422187.html, = "Assigned To";
assignedToColumn.DataPropertyName = "AssignedTo";
assignedToColumn.AutoComplete = true;
assignedToColumn.DisplayMember = "Name";
assignedToColumn.ValueMember = "Self";

// Add a button column.
DataGridViewButtonColumn buttonColumn =
new DataGridViewButtonColumn();
buttonColumn.HeaderText = "";
https://www.360docs.net/doc/c63422187.html, = "Status Request";
buttonColumn.Text = "Request Status";
https://www.360docs.net/doc/c63422187.html,eColumnTextForButtonValue = true;

dataGridView1.Columns.Add(idColumn);
dataGridView1.Columns.Add(assignedToColumn);
dataGridView1.Columns.Add(buttonColumn);

// Add a CellClick handler to handle clicks in the button column.
dataGridView1.CellClick +=
new DataGridViewCellEventHandler(dataGridView1_CellClick);
}

// Reports on task assignments.
private void reportButton_Click(object sender, EventArgs e)
{
StringBuilder report = new StringBuilder();
foreach (Task t in tasks)
{
String assignment =
t.AssignedTo == null ?
"unassigned" : "assigned to " + https://www.360docs.net/doc/c63422187.html,;
report.AppendFormat("Task {0} is {1}.", t.Id, assignment);
report.Append(Environment.NewLine);
}
MessageBox.Show(report.ToString(), "Task Assignments");
}

// Calls the Employee.RequestStatus method.
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// Ignore clicks that are not on button cells.
if (e.RowIndex < 0 || e.ColumnIndex !=
dataGridView1.Columns["Status Request"].Index) return;

// Retrieve the task ID.
Int32 taskID = (Int32)dataGridView1[0, e.RowIndex].Value;

// Retrieve the Employee object from the "Assigned To" cell.
Employee assignedTo = dataGridView1.Rows[e.RowIndex]
.Cells["Assigned To"].Value as Employee;

// Request status through the Employee object if present.
if (assignedTo != null)
{
assignedTo.RequestStatus(taskID);
}
else
{
MessageBox.Show(String.Format(
"Task {0} is unassigned.", taskID), "Status Request");
}
}

}

public class Task
{
public Task(Int32 id)
{
idValue = id;
}

public Task(Int32 id, Employee assignedTo)
{
idValue = id;
assignedToValue = assignedTo;
}

private Int32 idValue;
public Int32 Id
{
get { return idV

alue; }
set { idValue = value; }
}

private Employee assignedToValue;
public Employee AssignedTo
{
get { return assignedToValue; }
set { assignedToValue = value; }
}
}

public class Employee
{
public Employee(String name)
{
nameValue = name;
}

private String nameValue;
public String Name
{
get { return nameValue; }
set { nameValue = value; }
}

public Employee Self
{
get { return this; }
}

public void RequestStatus(Int32 taskID)
{
MessageBox.Show(String.Format(
"Status for task {0} has been requested from {1}.",
taskID, nameValue), "Status Request");
}
}




相关主题
相关文档
最新文档