替换DataGridView列真/假

问题描述:

我有一个DataGridView,我往里面如下:

I have a datagridview which I fill it as below :

var q= repository.GetStudents();//

dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();

dataGridView1.DataSource = q;

dataGridView1.Columns.RemoveAt(1);
//Remove IsActive 
//Cause I want to have my own implementation 

dataGridView1.Columns[0].DataPropertyName = "StudentID";
dataGridView1.Columns[0].HeaderText = "Studunet ID";

dataGridView1.Columns[1].DataPropertyName = "IsActive";
dataGridView1.Columns[1].HeaderText = "Status";



IsActive属性是布尔类型。当正在显示IsActive单元,它显示出真/假。我想用我自己的自定义值来取代它。

The "IsActive" property is of boolean Type. When the "IsActive" cell is being displayed, it show true/false. I want to replace it with my own custom value.

我读的这个并的这个帖子的,但我解决不了我的问题。

I read this and this posts but I could not resolve my problem.

您可以使用的CellFormatting DataGridView的,如的事件:

You can use the CellFormatting event of the DataGridView, e.g.:

void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var grid = (DataGridView)sender;
    if (grid.Columns[e.ColumnIndex].Name == "IsActive")
    {
        e.Value = (bool)e.Value ? "MY_TEXT_FOR_TRUE" : "MY_TEXT_FOR_FALSE";
        e.FormattingApplied = true;
    }
}






修改(按评论):

这是非常相似的,你现在在做什么,只是删除绑定列,并添加一个新列所需的类型和设置 DataPropertyName 如正常

It's very similar to what you're doing now, just remove the bound column and add a new column of the desired type and set the DataPropertyName properly e.g. :

this.dataGridView1.Columns.Remove("COL_TO_CUSTOMIZE");
var btnCol = new DataGridViewDisableButtonColumn();
btnCol.Name = "COL_TO_CUSTOMIZE";
btnCol.DataPropertyName = "COL_TO_CUSTOMIZE";
var col = this.dataGridView1.Columns.Add(btnCol);

请注意,此附加列在最后,但你可以通过使用决定列的位置 dataGridView.Columns.Insert 方法,而不是添加

Note that this append the column at the end, but you can decide the position of the column by using dataGridView.Columns.Insert method instead of Add.