根据特定条件在datagridview列中显示图像

本文关键字:显示 显示图 图像 datagridview 特定条件 | 更新日期: 2023-09-27 18:30:09

我正在使用以下代码填充DatagGridView

using (DataTable dtLLV = new DataTable())
{
    daLLV.Fill(dtLLV);
    dgSSW.AutoGenerateColumns = false;
    dgSSW.VirtualMode = true;
    dgSSW.ColumnCount = 5;
    var col0 = new DataGridViewTextBoxColumn
    {
        HeaderText = "Q. No.",
        Name = "RowNum",
        ReadOnly = true,
        Width = 70
    };
    dgSSW.Columns.Insert(0, col0);
    dgSSW.CellFormatting += GridCellFormatting;
    dgSSW.Columns[1].Name = "subsec_name";
    dgSSW.Columns[1].HeaderText = "Sub Section Name";
    dgSSW.Columns[1].DataPropertyName = "subsec_name";
    dgSSW.Columns[1].Width = 210;
    dgSSW.Columns[2].Name = "rt_correct_ans";
    dgSSW.Columns[2].HeaderText = "Correct Answer";
    dgSSW.Columns[2].DataPropertyName = "rt_correct_ans";
    dgSSW.Columns[3].Name = "rt_your_ans";
    dgSSW.Columns[3].HeaderText = "Your Answer";
    dgSSW.Columns[3].DataPropertyName = "rt_your_ans";

    dgSSW.Columns[4].Name = "q_r_difficulty";
    dgSSW.Columns[4].HeaderText = "Difficulty Level";
    dgSSW.Columns[4].DataPropertyName = "q_r_difficulty";
    dgSSW.Columns[5].Name = "rt_quest_all_s";
    dgSSW.Columns[5].HeaderText = "qid";
    dgSSW.Columns[5].DataPropertyName = "rt_quest_all_s";
    dgSSW.Columns[5].Visible = false;
    dgSSW.DataSource = dtLLV;
    var col3 = new DataGridViewImageColumn { HeaderText = "Result", Name = "Pic",Image=imgList.Images[0] };
    dgSSW.Columns.Insert(4, col3);
    var col7 = new DataGridViewButtonColumn
    {
        HeaderText = "Action",
        Name = "Action",
        Text = "View",
        UseColumnTextForButtonValue = true
    };
    dgSSW.Columns.Add(col7);
    dgSSW.CellContentClick += GridCellContentClick;
}//data table closed and disposed here

现在,如果下面提到的两个数据绑定列的DB值相等,我想在DataGridViewImageColumn中显示一个图像。如何在GridCellFormatting事件中进行这些相等性检查?我在获胜形式中使用C#。

dgSSW.Columns[2].Name="rt_correct_ans";

等于

dgSSW.Columns[3]。Name="rt_your_ans";

Basically, here "rt_correct_ans" & "rt_your_ans" are Table fields which store Integer values like
> rt_correct_ans | rt_your_ans
--------------------------------
1              | 3
2              | 2
4              | 4
5              | 0
........
So i want to check 
if(rt_correct_ans ==  rt_your_ans)
{
  show image 1;
}
else
{
 show image 2;
}

根据特定条件在datagridview列中显示图像

根据@Chris的建议如何根据条件更改DataGridView列值I、 现在已经在GridCellFormatting事件中修改了我的代码,如下所示

if (dgSSW.Columns[e.ColumnIndex].Name == "Pic")
{
    if(Convert.ToInt32(this.dgSSW.Rows[e.RowIndex].Cells[2].Value) == Convert.ToInt32(this.dgSSW.Rows[e.RowIndex].Cells[3].Value))
    {
        e.Value = imgList.Images[0];
    }
    else
    {
        e.Value = imgList.Images[1];
    }
}

它解决了我的问题:)。感谢@Chris和@Reza