65.9K
CodeProject 正在变化。 阅读更多。
Home

为 Windows Forms 数据绑定组合框添加“选择”选项 - 简单方法

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.43/5 (4投票s)

2009年10月23日

CPOL

1分钟阅读

viewsIcon

33283

如何用一种简单的方法为 Windows Forms 数据绑定组合框添加“选择”选项

引言

许多开发人员的常见任务是在 combobox 的开头插入一个项目,例如“选择一个选项”或类似的内容。

在 Windows Forms 中,这个选项的问题在于你不能简单地将这个新项目添加到绑定的 combobox 中。 新项目需要添加到 combobox 绑定的 datasource 中。

我创建了一个辅助方法,它接受你现有的 datatable,接收一些参数,并输出一个包含你新添加值的 datatable。 然后,你将 combobox 绑定到这个新的 datatable

让我们看一些代码来使这个更清晰...

Using the Code

public static DataTable GetComboBoxedDataTable
	(DataTable oldDataTable, string valueColumn, string textColumn, 
  	string topRowValue, string topRowText)
{
DataTable newDataTable = new DataTable();
newDataTable.Columns.Add(valueColumn);
newDataTable.Columns.Add(textColumn);

foreach (DataRow oldDR in oldDataTable.Rows)
{
  DataRow newDR = newDataTable.NewRow();
  newDR[0] = oldDR[valueColumn].ToString();
  newDR[1] = oldDR[textColumn].ToString();
  newDataTable.Rows.InsertAt(newDR, newDataTable.Rows.Count);
}

// Add your 'Select an item' option at the top
DataRow dr = newDataTable.NewRow();
dr[0] = topRowValue;
dr[1] = topRowText;
newDataTable.Rows.InsertAt(dr, 0);

return newDataTable; 
}

这个方法接受 5 个参数

  • oldDataTable - 这是你已经从数据库绑定到的 datatable
  • valueColumn - 这是你的 datatable 中你绑定到 comboboxValueMember 字段的列的名称。
  • textColumn - 这是你的 datatable 中你绑定到 comboboxDisplayMember 字段的列的名称。
  • topRowValue - 这是你添加到 combobox 的“选择”选项的值。
  • topRowText - 这是你添加到 combobox 的“选择”选项的显示文本。

这个辅助方法的优点在于,它不关心原始 datatable 中有多少列。 它只提取你需要的列用于你的 combobox,因为标准的 combobox 只支持两列。

要使用这个方法,这里有一个例子...

DataSet ds = GetDataSetFromMyDatabase();
comboBox.DataSource = GetComboBoxedDataTable(ds.Tables[0], 
	"ID", "EmployeeName", "0", "All Employees");

就这样了,一个辅助方法可以让你轻松地将“选择”选项添加到绑定的 combobox 中。

历史

  • 2009年10月23日:初始发布
© . All rights reserved.