トップ回答者
DataGridView 16進数表示設定した時、入力値が正しく反映されない

質問
-
Visual Studio 2010, C#を使用しております。
1.string 型とint 型のメンバ変数を含んだクラスを、ArrayListに追加します。
2.そのデータを、フォーム上に配置した DataGridView とバインドし、値を表示しています。
3.DataGridView のある列の書式を16進数表示に変更します。
DataGridView.Columns[n].DefaultCellStyle.Format = "X8";
4.16進表示した状態の DataGridView の値を変更すると、
入力がだたしく反映されません。
具体的には、
表示する元データ = 8470
16進数表示したデータ = 2116この時に 2116 を 2117 変更し、Enterキーを押すと
DataGridView の表示は 845 となってしまいます。入力した 2117 を10進数だと判断し、16進表示で 845 と表示していると思います。
16進数表示したデータ = 2116 を 2117 と変更した場合、
DataGridView の表示を 2177 にするにはどのような対処をすればよいのでしょうか。よろしくお願いいたします。
回答
-
こんな
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { if(e.InheritedCellStyle.Format=="X8") { int i; if (int.TryParse(e.Value.ToString(), System.Globalization.NumberStyles.HexNumber, null, out i)) { e.Value = i; e.ParsingApplied = true; } else//int.MaxValue超えてるとか変な文字とか { var dgv=(DataGridView)sender; e.Value = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; e.ParsingApplied = true; } } }
個別に明示されていない限りgekkaがフォーラムに投稿したコードにはフォーラム使用条件に基づき「MICROSOFT LIMITED PUBLIC LICENSE」が適用されます。(かなり自由に使ってOK!)- 回答としてマーク cow bell 2011年11月30日 1:14
すべての返信
-
こんな
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { if(e.InheritedCellStyle.Format=="X8") { int i; if (int.TryParse(e.Value.ToString(), System.Globalization.NumberStyles.HexNumber, null, out i)) { e.Value = i; e.ParsingApplied = true; } else//int.MaxValue超えてるとか変な文字とか { var dgv=(DataGridView)sender; e.Value = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; e.ParsingApplied = true; } } }
個別に明示されていない限りgekkaがフォーラムに投稿したコードにはフォーラム使用条件に基づき「MICROSOFT LIMITED PUBLIC LICENSE」が適用されます。(かなり自由に使ってOK!)- 回答としてマーク cow bell 2011年11月30日 1:14
-
gekka 様
ご回答いただきありがとうございます。
ご紹介いただいたコードで解決しました。投稿前は下記コードで判定を行おうと思っていたのですが
うまくいかず困っておりました。private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int buf = 0;
if (this.radioButtonHex.Checked == true)
{
if (int.TryParse(e.FormattedValue.ToString(), System.Globalization.NumberStyles.HexNumber, null, out buf) == false)
{
dataGridView.Rows[e.RowIndex].ErrorText = "入力エラー(16進数)";
e.Cancel = true;
}
else
{
}
}
}ありがとうございました。