Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Could you please help me out with this problem, I have a column in my SQL table as type of bit (for example, a column of gender) so when loading the table, the DataGridView shows me a column of checkboxes without any text, the male gender is checked (the bit value is 1) and female gender is unchecked (the bit value is 0). I don't like it that way which looks ugly to me, I want to customize or do something to format the content of each cell in that column of DataGridViewCheckBoxCell so that a string of "Male" replaces the checked checkbox and a string of "Female" replaces the unchecked checkbox.

The problem will be sorted out easily if I change my original column to another column type like varchar to store the strings of "Male" and "Female" directly, but I like to use bit instead, maybe it's a way to save storage, isn't it?

Thank you for your help!
Posted

One way this could be done is to create a custom DataGridView column as described here[^].
 
Share this answer
 
Thank you Mike Hankey for the good link, inheriting DataGridViewCell and DataGridViewColumn is OK but it is not simple enough and I chose another solution which only adds some lines of code to the CellPainting handler of the datagridView, here is the code I tried, it works perfectly:

C#
private void HS_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (HS.Columns[e.ColumnIndex].CellTemplate.GetType() == typeof(DataGridViewCheckBoxCell)&&e.RowIndex > -1)
            {
                e.Handled = true;                
                string s = (bool)e.Value ? "Male" : "Female";
                e.PaintBackground(e.CellBounds, HS.CurrentCellAddress.Y == e.RowIndex);
                StringFormat sf = new StringFormat();
                sf.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(s, HS.Font, new SolidBrush(HS.ForeColor), e.CellBounds,sf);                
            }
        }


Thanks!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900