简体   繁体   中英

Unable to print integer value using Response.Write()

I have following code that prints some list. The list is printing but the value of integer variable i is not printing.

<%
int i = 1;
try
{
    foreach (LElement r in LElements)
    {
        Response.Write("<br/><div style=\"font-size:small\">");
        Response.Write("Element "+i+"="+r.name);
        Response.Write("</div>");
        i++;
    }
    Response.Write("<br/>");
}
catch (Exception)
{
    Response.Write("Error");
}
%>

Its just printing

Element = ABC

Element = XYZ

and so on...

Resulting HTML is somewhat like this:

<br/><div style="font-size:small">Element = ABC</div>
<br/><div style="font-size:small">Element = XYZ</div>
<br/><div style="font-size:small">Element = PQR</div><br/>

Please tell me what is wrong with this code?

I've tried reproducing your issue and can't so I am guessing either your sample code is quite different from your real code or something deeper is going on? This is what I've done and works OK so you could take this as a starting point and tell us if it works any more than your code and might highlight any mistakes you have made?

<%    
    string[] data = { "ABC", "DEF", "GHI", "XYZ" };
    int i = 1;

    try
    {
        foreach(string item in data)
        {
            Response.Write("<br/><div style=\"font-size:small\">");
            Response.Write(String.Format("Element {0} = {1}", i, item));
            Response.Write("</div>");
            i++;
        }
        Response.Write("<br/>");
    }
    catch (Exception) 
    { 
        Response.Write("Error");
    }
%>

PS I've wrapped the output into a String.Format which will ensure it gets converted to a string correctly.

Response.Write(String.Format("Element {0} = {1}", i, r.name));

Try this:

Response.Write(String.Format("Element {0} = {1}", i, r.name));

Edit: Zarathos was ahead of me :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM