line break in DataTable and GridView

这一生的挚爱 提交于 2020-01-06 04:35:11

问题


I am actually trying to put a line break in a string in an asp.net project using c#.I put this String in a DataRow that I add to a datable named "ds".Once it's done I link this datable ds to the gridview. This is my code:

            risque.projet = dt.Rows[i]["fk_projet"].ToString();
            risque.release = dt.Rows[i]["fk_release"].ToString();

            //Create the String for adding to the row
            String test = "Project:"+risque.projet+"<br>"+ "Release: "+risque.release;
            drow["Description"] = test;
            Label1.Text = test;


            //Add the row to the datatable.
            ds.Rows.Add(drow);

            //Link the datatable to the gridview
            GridView1.DataSource = ds;
            GridView1.DataBind();

I want this output:

Project:.......

Release:.......

but I always have : Project:.... Release......

I tried many solutions: -System.Environment.NewLine -\r\n -\n

EDIT:Code of my gridView.I have nothing in my gridview because all is created at runtime.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        EnableSortingAndPagingCallbacks="True" PageSize="5">
        <SelectedRowStyle Wrap="True" />
    </asp:GridView>

But nothing works. The br tag works but only when I display my String in a label.

Do you have an idea of my error?Do you have a solution? I spent too much time on this.

Thank you,

Quentin


回答1:


It should work put the tag in, but set the column's HtmlEncode property to false. By default all fields are HtmlEncoded, which of course, stops html tags from working like html tags.

However, if you're doing this, you'll want to htmlencode the field values manually in code-behind to prevent XSS.

"Project:" + Server.HtmlEncode(risque.projet )+ "<br />" + "Release: " + Server.HtmlEncode(risque.release)

(I prefer the Anit-Cross-Site Scripting Library's implemmentation of HtmlEncode to Server.HtmlEncode, but that's another subject.)




回答2:


Instead of concatenating break tags you could use a carriage-return character, vbCrLf in this case.

Carriage-return characters are used for print and display functions.

However, vbCrLf does not exist in C#. The value of vbCrLf is "\r\n". So try this below.

string vbCrLf = "\r\n";
String test = "Project:" + risque.projet + vbCrLf + "Release: " + risque.release;



回答3:


I think you need: <br /> instead of <br>




回答4:


Convert the grid column into template column and the label will do the magic. The
will work if binding data to a label.



来源:https://stackoverflow.com/questions/10450024/line-break-in-datatable-and-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!