WindowsFormのDataGridViewに以下のイベントを追加することで、
オブジェクトに「○○.××」のようなバインディングを可能とする
/// <summary>
/// セルの内容が書式用に変更されなければならない時にコールバックされます。
/// </summary>
/// <param name="sender">イベント発生元</param>
/// <param name="e">イベント引数</param>
private void dgvSettingList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
EventUtils.Grid_CellFormatting(sender, e);
}
補助クラス
補助クラス
public class EventUtils
{
/// <summary>
/// グリッドのバインディングの値をコールバックします。
/// </summary>
/// <param name="sender">イベント発生元</param>
/// <param name="e">イベント引数</param>
public static void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var grid = (DataGridView)sender;
if ((grid.Rows[e.RowIndex].DataBoundItem != null) &&
(grid.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
{
e.Value = PropertyUtils.BindProperty(
grid.Rows[e.RowIndex].DataBoundItem,
grid.Columns[e.ColumnIndex].DataPropertyName
);
}
}
}
public static class PropertyUtils
public static class PropertyUtils
{
}
public static string BindProperty(object property, string propertyName)
{
string retValue = "";
if (propertyName.Contains("."))
{
var leftPropertyName = propertyName.Substring(0, propertyName.IndexOf(".", System.StringComparison.Ordinal));
var arrayProperties = property.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in arrayProperties)
{
if (propertyInfo.Name == leftPropertyName)
{
retValue = BindProperty(
propertyInfo.GetValue(property, null),
propertyName.Substring(propertyName.IndexOf(".", System.StringComparison.Ordinal) + 1));
break;
}
}
}
else
{
var propertyType = property.GetType();
var propertyInfo = propertyType.GetProperty(propertyName);
retValue = propertyInfo.GetValue(property, null).ToString();
}
return retValue;
}
}
コメント