Si8
Si8

Reputation: 9235

How to show new line in a GridView column

I have the following C# function:

public string CheckInCollection(long lngProvId)
{
    //...
    foreach (var item in collList)
    {
        strColl += item.Id.ToString() + " (" + item.Title + ")" + "\r\n";
    }

    return strColl;
}

The following C# function:

public void PopulateGridView(bool blType)
{
    if (blType == false)
    {
    }
    else
    {
        strCollFinalized = "" + ddlContent.SelectedItem + "|" + CheckInCollection(Convert.ToInt64(ddlContent.SelectedItem.Value)) + "";
        string[] strL = strCollFinalized.Split('|');

        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Provider");
        DataColumn dc1 = new DataColumn("Collection");

        dt.Columns.Add(dc);
        dt.Columns.Add(dc1);

        DataRow dr = dt.NewRow();
        dr[dc] = strL[0];
        dr[dc1] = strL[1];

        dt.Rows.Add(dr);
        gvData.DataSource = dt;
        gvData.DataBind();
    }
}

When the gridview is generated the second column is displayed in one line but when I check the source, it is displaying in the next line.

How can I modify so that the returned string shows each strColl in a new line.

Upvotes: 1

Views: 9013

Answers (1)

Jhon
Jhon

Reputation: 582

As @user2169261 suggested, you can add <br> instead of \r\n

Then you can set the HtmlEncode property of the column you want to show the newline to false.

For example:

<Columns>
    <asp:BoundField DataField="Whatever" HtmlEncode="False" />
</Columns>

For autogenerated columns, you can try following approach (as per this answer)

Make your own inspection of the DataTable and create an explicit BoundColumn for each column:

foreach (DataColumn column in dt.Columns)
{
    GridViewColumn boundColumn = new BoundColumn
    {
        DataSource = column.ColumnName,
        HeaderText = column.ColumnName,
        HtmlEncode = false
    };
    gvData.Columns.Add(boundColumn);
}

gvData.DataSource = dt;
gvData.DataBind();

Upvotes: 6

Related Questions