是否有datagridview_CellFormating用于格式化dataGridView中的单元格显示?

时间:2019-03-23 05:15:01

标签: c# winforms datagridview

我正在做一个管理学生的应用程序。它将数据从SQL server加载到DataGridView。我的表格有一个Boolean字段,名称为性别。 将表格加载到DataGridView中后,“性别”列仅显示在复选框类型下。我想将其表示方式更改为另一种方式,而不是像这样的复选框。 (字符串显示“ 男性”或“ 女性”)。

Appication Captured

我尝试了许多在google上搜索的解决方案。但是我找不到解决问题的方法。

SQL创建表代码:

create table Student
(
    CodeSV varchar(5) not null primary key,
    FirstnameSV varchar(20) not null, 
    LastnameSV varchar(30) not null, 
    BirthDate date,
    Gender bit not null,
)

对象属性:

public int CodeSV{ get; set; }
public string FirstnameSV { get; set; }
public string LastnameSV { get; set; }
public DateTime BirthDate { get; set; }
public bool Gender { get; set; }

我使用以下代码在DataGridView中显示数据:

List<Object> list = new List<Object>();
BindingSource bs = new BindingSource();
list = ObjectDAO.ListAllStudent();
if (list != null)
{
    bs.DataSource = list;
    dgvManager.DataSource = bs;
    dgvManager.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}

2 个答案:

答案 0 :(得分:1)

由于为此使用了Class,因此我建议您对其进行修改以按照您的描述进行操作。当将List<T>用作网格的DataSource时,该类的“公开”公开(非集合)属性将映射到网格中的列。在这种情况下,Gender字段是布尔值,将显示为复选框。

要将此值显示为字符串值(男性/女性)…那么我建议您在Student类中创建此“属性”…。像下面这样……

public string GenderString {
  get {
    if (Gender) {
      return "Male";
    }
    return "Female";
  }
}

这会将GenderString列“添加”到网格。如果您不希望显示Gender“布尔”列,则可以使其在网格中不可见,也可以使Gender属性private.成为{{ 1}}属性Gender,您需要使用公共的“设置”方法来设置其值;

希望这会有所帮助。

答案 1 :(得分:1)

您可能正在寻找dataGridView_CellPainting事件。

您可以在此处绘制具有所需内容的字符串,并使用各种内置的辅助功能来绘制单元格应显示的其他内容。

完成后,设置e.Handled = true;以防止普通绘画覆盖您的东西。

示例在左侧显示复选框,在右侧显示文本:

enter image description here

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if ( e.RowIndex >= 0 && e.ColumnIndex == 0)
    {
        Brush br = e.State.HasFlag(DataGridViewElementStates.Selected) ?
            SystemBrushes.HighlightText : SystemBrushes.WindowText;
        Font font = dataGridView1.DefaultCellStyle.Font;
        Rectangle r2 = new Rectangle(e.CellBounds.X + 24, e.CellBounds.Y, 
            e.CellBounds.Width - 24, e.CellBounds.Height);

        e.PaintBackground(e.CellBounds, true);

        using (StringFormat fmt = new StringFormat()
        { LineAlignment = StringAlignment.Center})
           if (e.Value != null) e.Graphics.DrawString(e.Value.ToString(), font, br, r2, fmt);

        e.PaintContent(e.CellBounds);
        e.Handled = true;
    }
}

我很懒,并且使用一个幻数(24)作为偏移量,但是如果需要,可以通过多种方法以更灵活的方式确定最佳值。

像这样对齐单元格:

dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleLeft;

由于DGV复选框在用户离开单元格之前不会相信其更改,因此我们需要按预期的那样工作:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

注意:ToString产生的值在此处TrueFalse。如果您将复选框设置为允许第三种状态(ThreeState = true),则将分别为CheckedUncheckedIndeterminate。然后由您来测试这些内容并显示所需的字符串。

正如我在评论中指出的那样,您实际上应该允许至少一个替代性别未定状态;因此,CheckBox并不是最好的选择。不要考虑使用下拉列表!