Search code examples
c#asp.netdatagridview

How to insert an html icon into a datagridview


I am trying to put a html icon into a datagridview row to show when a folder is locked. The code below currently only display a "Yes" in datagridview row when a folder is locked. I want to replace the "Yes" with a html icon.

// Creating a new DataTable.
DataTable custTable = new DataTable("folders");
DataColumn dtaColumn;
DataRow myDataRow;

// Create id column
dtaColumn = new DataColumn();
dtaColumn.DataType = typeof(string);
dtaColumn.ColumnName = "Type";
dtaColumn.Caption = "Type";
custTable.Columns.Add(dtaColumn);

dtaColumn = new DataColumn();
dtaColumn.DataType = typeof(String);
dtaColumn.ColumnName = "Description";
dtaColumn.Caption = "Description";
dtaColumn.ReadOnly = false;
dtaColumn.Unique = false;
custTable.Columns.Add(dtaColumn);

dtaColumn = new DataColumn();
dtaColumn.DataType = typeof(String);
dtaColumn.ColumnName = "Size";
dtaColumn.Caption = "Size";
dtaColumn.ReadOnly = false;
dtaColumn.Unique = false;
custTable.Columns.Add(dtaColumn);

dtaColumn = new DataColumn();
dtaColumn.DataType = typeof(String);
dtaColumn.ColumnName = "Locked";
dtaColumn.Caption = "Locked";
dtaColumn.ReadOnly = false;
dtaColumn.Unique = false;
custTable.Columns.Add(dtaColumn);

dtaSet = new DataSet();
dtaSet.Tables.Add(custTable);

string[] subdirectoryEntries = Directory.GetDirectories(Server.MapPath(pathToFollow));

//creating rows
foreach (string folderPath in subdirectoryEntries)
{   
    myDataRow = custTable.NewRow();

    myDataRow["Type"] = "Folder";
    myDataRow["Description"] = Path.GetFileName(folderPath);
    myDataRow["Size"] = "NA";
    
    //checking if folder is locked
    for(int i = 0; i<pathLock.Count; i++)
    {
        if (pathLock[i] == folderPath)
        {
            myDataRow["Locked"] = "Yes"; //Place to insert the icon
        }
    }
    custTable.Rows.Add(myDataRow);
}

Code for the html icon

<span class="fa fa-lock"></span>

This is how my current code looks.


Solution

  • Use the rowdatabound event of the gridview:

    void gridview_rowdatabound(...)
    {
        if (e.row.rowtype == datacontrolrowtype.datarow)
        {
            if (e.row.cells[2].text == "Locked")
            {
                e.row.cells[2].text = "<span class='fa fa-lock'></span>";
            }
        }
    }
    

    Assuming the column index of Locked is 2.