添加一个“选择”选项到一个Windows Forms Databound组合框-简单的方法

介绍 许多开发人员的常见任务是在组合框的开头插入一个项,例如“Select an option”或类似的内容。 这个选项在Windows窗体中的问题是,您不能简单地将这个新项添加到绑定组合框中。需要将新项添加到组合框绑定到的数据源。 我已经创建了一个助手方法,它接受现有的datatable,接受

  

 

几个参数,并使用新添加的值输出datatable。然后将您的组合框绑定到这个新的数据表。 让我们看一些代码,使之更清楚…… 使用的代码 隐藏,复制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——这是您已经绑定到的数据表。valueColumn -这是您绑定到组合框的ValueMember字段的datatable中的列的名称。textColumn——这是datatable中绑定到组合框的DisplayMember字段的列的名称。topRowValue——这是你添加到组合框中的“选择”选项的价值。topRowText——这是你添加到组合框中的“选择”选项所显示的文本。 这个helper方法的好处是,它与原始datatable中有多少列无关。它只去除combobox所需的列,因为标准的combobox只支持两列。 为了使用这个方法,这里有一个例子… 隐藏,复制Code

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

这就是帮助器方法,它可以让你轻松地在绑定组合框中添加一个“Select”选项。 历史 2009年10月23日:初任 本文转载于:http://www.diyabc.com/frontweb/news163.html

posted @ 2020-08-04 00:55  Dincat  阅读(227)  评论(0编辑  收藏  举报