Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c# - replace true/false in datagridview columns

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";

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

EDIT (as per comment):

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...