1

Check my code below:

HTML Page:

<table width="100%" align="right" cellpadding="2" cellspacing="2" border="0" bgcolor="#EAEAEA">
    <tr align="center" style="background-color: yellow; color: black;">
        <th colspan="2">Fauzan</th>
        <th colspan="2">Febri</th>
    </tr>
    <tr align="left" style="background-color: gray; color: black;">
        <td>ID</td>
        <td>Number01</td>
        <td>TheDate</td>
        <td>Number02</td>
    </tr>
    <%=getWhileLoopData()%>
</table>

Code Behind:

public string getWhileLoopData() 
{
 string htmlStr = "";
 SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
 SqlCommand thisCommand = thisConnection.CreateCommand();
 thisCommand.CommandText = "SELECT * FROM MyTable WHERE TheDate = @TheDate";
 thisCommand.Parameters.AddWithValue("@TheDate", txtDate.Text);

 thisConnection.Open();
 SqlDataReader reader = thisCommand.ExecuteReader();

 while (reader.Read()) {
     int id = reader.GetInt32(0);

     int Number01 = reader.GetInt32(1);
     DateTime TheDate = reader.GetDateTime(2);
     Decimal Number02 = reader.GetDecimal(3);

     //string Pass = reader.GetString(2);
     htmlStr += "<tr><td>" + id + "</td><td>" + Number01 + "</td><td>" + TheDate + "</td><td>" + Number02 + "</td></tr>";
 }

 thisConnection.Close();
 return htmlStr;
}

The question is, how can i format the data reader? Like, "TheDate" field, from '6/18/2014 12:00:00 AM' to '18/Jun/2014'. Also for 'Number02' field, how can i format it? Like, from '0.829' become '0.83'.

1 Answer 1

2

You can format datetime using ToString() with Custom Date and Time Format Strings

string strDate = TheDate.ToString("dd/MMM/yyyy");

You can use Math.Round to format number

Number02 = Math.Round(Number02, 2);

You can directly format date and number in the html string you are making

htmlStr += "<tr><td>" + id + "</td><td>" + Number01 + "</td><td>" +
   TheDate.ToString("dd/MMM/yyyy") + "</td><td>" +  Math.Round(Number02, 2) + "</td></tr>";
Sign up to request clarification or add additional context in comments.

3 Comments

Hey mate, it works! Thank you so much. Also another one, how can i format number? Like, From 1200 to 1,200. Want to use comma as a separator. And probably want also to put .00 after the number. Cheers,
You can use something like, String.Format("{0:n2}", 1234)
Hey mate, from my question above.. How can i put the total of Number 02 on html table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.