Ankit Tyagi
Ankit Tyagi

Reputation: 175

How to format string in gridview in c#

I am fetching Two Columns from database, one column has data type as varbinary. I am converting the varbinary column to byte[] and then to string. Code is working for console application and keeping the string format. But when i am using the same code in Web Application and displaying the data in GridView, it losing the format. For Ex:

Hello

World

will be displaying as Hello World in Grid View. Here is my code :

    SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=legal; Integrated Security=True");
    SqlCommand cmd = new SqlCommand("usp_output_repayment  @id=1", con);

    con.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Columns.Add("Category");
    dt.Columns.Add("Description");

    while (dr.Read())
    {
    DataRow dr1 = dt.NewRow();

        dr1["Category"] = dr[0];
        dr1["Description"] = System.Text.ASCIIEncoding.ASCII.GetString((byte[])dr[1]).Normalize();
        dt.Rows.Add(dr1);


    }

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

Upvotes: 0

Views: 680

Answers (1)

Arslan Ali
Arslan Ali

Reputation: 460

When you are working on the asp.net side then you should use DataBound inside the gridview as well as setting AutoGenerateColumns="false"

Now it's my main point of view if you are getting description of whatever format as well then use HtmlEncode="false" for your column that you used

Few Code of GridView,that you will have to utilize as such format described.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Description" HeaderText="Description" HtmlEncode="false" />
        </Columns>
    </asp:GridView>

Error format that I could faced using HtmlEncode="true" or removing it

enter image description here

Tested and got well using HtmlEncode="false" upon following result

enter image description here

Upvotes: 1

Related Questions