如何通过DataTable为DataGridViewRow传递Tag属性值?
解决DataGridView绑定自定义DataTable时Tag属性无法传递的问题
这个问题我碰过不少次,核心原因很明确:DataGridView的DataGridViewRow对象和你自定义的MyDataRow是完全独立的实例,DataGridView不会自动把MyDataRow的Tag映射到对应的DataGridViewRow.Tag上,所以你在RowEnter事件里直接取row.Tag肯定是空的。
下面给你两种实用的解决思路,按需选择:
思路一:直接从绑定的数据源中获取Tag
既然你的Tag是存在MyDataRow里的,那在RowEnter事件中,我们可以先拿到当前行绑定的DataRowView,再转成你的MyDataRow,直接读取它的Tag属性:
private void DataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { // 排除标题行和新行(如果允许用户添加的话) if (e.RowIndex < 0 || e.RowIndex >= dataGridView1.Rows.Count || dataGridView1.Rows[e.RowIndex].IsNewRow) return; var rowView = dataGridView1.Rows[e.RowIndex].DataBoundItem as DataRowView; if (rowView == null) return; var myDataRow = rowView.Row as MyDataRow; if (myDataRow != null) { var l = (List<string>)myDataRow.Tag; // 在这里使用你的Tag数据即可 } }
这种方式不需要额外维护属性同步,直接从数据源取最可靠,适合大多数场景。
思路二:在Row创建时同步Tag到DataGridViewRow
如果你确实希望DataGridViewRow.Tag直接持有MyDataRow.Tag的值,可以处理DataGridView的RowCreated事件,在每行创建完成后手动同步:
private void DataGridView1_RowCreated(object sender, DataGridViewRowEventArgs e) { // 跳过新行 if (e.Row.IsNewRow) return; var rowView = e.Row.DataBoundItem as DataRowView; if (rowView == null) return; var myDataRow = rowView.Row as MyDataRow; if (myDataRow != null) { e.Row.Tag = myDataRow.Tag; } }
这样之后,你在RowEnter事件里直接读row.Tag就能拿到值了。不过要注意:如果后续MyDataRow.Tag的值发生变化,你需要手动更新对应的DataGridViewRow.Tag,否则会出现不同步的情况。
额外说明
你自定义的MyDataRow和MyDataTable的代码是没问题的,GetRowType和NewRowFromBuilder的重写正确保证了DataTable会创建你的自定义行实例,这部分不用改。
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

