DataGridView
コントロール名とデータベース テーブルのフィールドに表示しようとしています。テーブルのすべての行の名前が最初のセルに表示され、2 番目の列でそのテーブルの任意のフィールドを選択できます。
そのために、「DataGridView.CellBeginEdit」イベントを処理し、セルの DataSource にフィールドの名前を入力します。これらのセルを編集しようとすると、提供されたリストが正しく表示され、問題なく選択できます。
ただし、別の行で同じことをしようとすると、DataError
編集したセルに関するイベントが発生し始めます。
DataRow のイベント引数には、Context
フィールドに「Formatting|Display」があり、「DataGridViewComboBoxCell では値を使用できません」(またはそれに近い) というメッセージが表示されます。デバッグでは、セル イベント参照には正しいValue
フィールドがありますが、 DataSource
null であり、FormattedValue
空の文字列です。また、以前に表示されていたテキストが空白に変わります。
これはどのように正しく解決する必要がありますか? テキストを表示するがコンボボックス エディターを持つ独自のカスタム datagridview セルを派生させる必要がありますか? もしそうなら、どのように?
編集:ここに私が現在使用しているコードがあります:
public class FieldDataNeededEventArgs: EventArgs
{
public List<string> FieldNames
{
get; private set;
}
public string TableName
{
get; private set;
}
public ReferenceFieldDataNeededEventArgs(stringdata)
: base()
{
FieldNames = new List<string>();
TableName= data;
}
}
...
public event EventHandler<FieldDataNeededEventArgs> FieldDataNeeded =
new EventHandler<FieldDataNeededEventArgs>((sender, args) => { });
...
//handler for CellBeginEdit
//dgvMatch - dataGridView, DocsReferenceToTableMatch is class that datagridview is bound to
private void dgvMatch_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == dgvMatch.Columns["TableKey"].Index)
{
DocsReferenceToTableMatch data = dgvMatch.Rows[e.RowIndex].DataBoundItem as DocsReferenceToTableMatch;
FieldDataNeededEventArgs ea = new FieldDataNeededEventArgs(data.TableName);
FieldDataNeeded(this, ea);
var cell = (dgvMatch.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell);
cell.DataSource = ea.FieldNames;
}
}
//example handler for the FieldDataNeeded event
static void ld_ReferenceFieldDataNeeded(object sender, ReferenceFieldDataNeededEventArgs e)
{
for (int i = 0; i < 4; i++)
{
e.FieldNames.Add(String.Format("{0}_fld{1}", e.ReferenceName, i));
}
}