C++ DataGridView 中的日期时间选择器





5.00/5 (4投票s)
C++ DataGridView 中的日期时间选择器

引言
我到处搜索,却找不到一篇使用 C++ .NET 在 Windows Forms 中演示如何将 datetimepicker
添加到 DataGridView
,并且允许 null
值的文章。虽然有很多使用 C# 的文章,但没有 C++ 的。
目的
本文旨在用 Visual Studio 2008 和 .NET 3.5 用 C++ 复制广泛可用的 Microsoft 文章。将其作为示例将使 C++.NET 开发者能够在 DataGridView
中部署一个可为空的 DateTimePicker
。
方法
作为我们的起点,是经常被引用的 Microsoft C# 文章:http://msdn.microsoft.com/en-us/library/7tas5c80.aspx。
下一个成分是 Tangible Software Solutions http://www.tangiblesoftwaresolutions.com/ 演示 C# 到 C++ 转换器。
但是演示只能处理 100 行代码,而 Microsoft 示例有 246 行。因此,首先删除空白行,然后删除所有注释,最后删除许多换行符,以便将多个语句放在同一行上。
这是一个例子
public CalendarCell()
: base()
{
// Use the short date format.
this.Style.Format = "d";
}
变成了
public CalendarCell(): base()
{ this.Style.Format = "d"; }
之后,就是在 Visual Studio 2008 中启动一个新的 Windows Form 应用程序,并将转换后的代码粘贴到 .h 和 .cpp 文件中。转换后的代码中只有一个错误需要更正。Main
必须更改为 main
。这就是 DataGridDateTimeEx
,代码完全按照 Microsoft 网站的翻译结果。仅此而已,就生成了一个用 C++ .NET 编写的 DataGridView
中的 DateTimePicker
。
初始帖子中的 DataGridViewDateTimeEx2
是一个略微个性化的版本,例如,表单和 DataGridView
是从工具箱中拖放的,from_load
事件在这个例子中位于 .h 文件中,日期/时间列被移动到第三列并赋予了列标题。
我将其替换为 DataGridViewDateTimeEx5
。它仍然使用相同的转换代码,但现在每个类,CalendarCell
、CalendarColumn
和 CalendarEditingControl
都有自己的 .h 和 .cpp 文件。这既有助于可重用性,又保持了应用程序特定的 .h 和 .cpp 文件“干净”。
从这里,转换后的类可以进一步分解到它们自己的类库中,以便在多个模块中轻松重用。日历列(如果声明为 public
)现在被添加到列类型下拉菜单中,允许您使用表单设计器指定日期列的位置。

作为进一步的增强,我添加了一个按钮列,用于清除日期列之一。我查看了 CodeProject 上的 vic_ch2000 关于该主题的文章,但我无法可靠地用 C++ 复制他的 DatePicker
类,因此选择了 Button
方法。我将 CellContendClickEvent
添加到网格中,并对其进行了如下编程
private: System::Void dataGridView1_CellContentClick
(System::Object^ sender, System::Windows::Forms::DataGridViewCellEventArgs^ e) {
if (e->ColumnIndex != 4)
return; // Hardcoded to only accept the event on the button column
else
dataGridView1->Rows[e->RowIndex]->Cells[e->ColumnIndex-1]->Value = nullptr;
}
历史
- 2010 年 10 月 13 日:初始版本