LoginSignup
1
2

More than 5 years have passed since last update.

.NET FrameworkのDataGridViewに日付を追加する(C++)

Posted at

DataGridViewとは

フォームにエクセルのようなグリッドを作成します。
フォーム内のセルは自由に追加、削除できる機能がデーターグリッドビューには装備されています。データーグリッドビューは、Visual Studio C++ 2005バージョン以降から利用できるようになりました。

今回は、このグリッドに日付を追加してみます。下の図のDateの部分がそれになります。

image

C++コーディングの解説

.NETといえば、C#が最も多く使われる言語かもしれませんが、C++でも簡単にフォームアプリケーションが作成できます。C/C++に慣れている人は、同じ言語で作成したほうが作業が楽になります。

日付を取得するには#include <time.h>をインクルードします。
tm構造体を作成し、現在の時刻をlocaltime(&timer)で取得します。

構造体には9つのメンバがありますが、年と月には注意がいります。tm_yearは1900年からの年数、tm_monは0からの月数なので、それぞれ1900と1をプラスしてコードに書きます。

さらに、メンバはint型のため、Datagridiviewに追加するにはSystem::Stringの型に直しておく必要があります。

int→string→System::Stringへと変換します。

intからstringはC++なら単純に、stringstreamを使用するのが最も簡単だと思います。<sstream> と <string>をインクルードします。

setw()で桁数を設定し、setfill()で数字の隙間を0で埋めます。何も指定しなければ、2017年1月1日1時0分となると不格好な表示になってしまいます。これをPCらしく2017年01月01日01時00分のように表示させます。これを利用するには、#include <iomanip>をインクルードしてください。

stringstream ss;
ss << year << "/" << setw(2) << setfill('0') << month << "/" << setw(2) << setfill('0') << day << "," << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << seconds;

標準文字列を System::String に変換するには、String^ dateTime = gcnew String(getTime.c_str());のように記述します。この型に変換しないとグリッドに日付を表示できません。

グリッド横軸のデータ配列を作成します。日付、ID、Nameの順番になります。IDとNameもSystem::String の型に変換します。

array<String^>^ rows0 = gcnew array<String^>{dateTime,idNum,name};`

グリッドに追加します。DataGridViewRowCollectionでROW配列データまとめて追加します。

DataGridViewRowCollection^ rows = this->dataGridView1->Rows;
rows->Add(rows0);

image

今回作成したコード

ボタンクリックにコードをそのまま追加してもいいですが、関数にしてしまえばコードがわかりやすくなります。

    time_t timer = time(0);

    struct tm *timeStruct = localtime(&timer);

    int year = 1900 + timeStruct->tm_year;
    int month = 1 + timeStruct->tm_mon;
    int day = timeStruct->tm_mday;
    int hour = timeStruct->tm_hour;
    int minute = timeStruct->tm_min;
    int seconds = timeStruct->tm_sec;
    String^ idNum = textBox1->Text;
    String^ name = textBox2->Text;

    stringstream ss;
    ss << year << "/" << setw(2) << setfill('0') << month << "/" << setw(2) << setfill('0') << day << "," << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << seconds;
    string getTime = ss.str();
    String^ dateTime = gcnew String(getTime.c_str());

    array<String^>^ rows0 = gcnew array<String^>{dateTime,idNum,name};
    DataGridViewRowCollection^ rows = this->dataGridView1->Rows;
    rows->Add(rows0);



1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2