2013-11-21 24 views
0

在Asp.net段說我有
現在我想P中
顯示在h1和內容標題帶有屬性的標題和內容的信息的數據我怎麼使用for/while循環。使用C#Asp.net
產生這些標籤,以便其像這樣
標題和使用C#

標題1

內容

heading2

內容再次

,並不斷去.. ?

回答

0

我不確定是否理解,但是您的意思是說您獲取某種數據,並且想要以這種方式顯示?您應該使用ListView,在其中定義一個ItemTemplate,並將數據分配給DataSource屬性。

例如,在你的.aspx文件

<asp:ListView ID="LvPost" runat="server" OnItemDataBound="LvPost_ItemDataBound"> 
    <ItemTemplate> 
    <h1><asp:Literal id="title" runat="server"></h1> 
    <p><asp:Literal id="content" runat="server"></p> 
    </ItemTemplate> 
</asp:ListView> 

然後,在你LvPost_ItemDataBound方法類似

var postItem= e.Item.DataItem as YourPostClass; 
var h1Text = e.Item.FindControl("title") as Literal; 
var pText= e.Item.FindControl("content") as Literal; 
h1Text.Text=postItem.Title; 
pText.Text = postItem.Content; 

最後,不要忘記將數據綁定到列表視圖,(前:在PageLoad中)

LvPost.DataSource = <List of YourPostClass>; 
0

我不確定你的數據到底如何,但是像這樣可能會工作。把文字在網頁上,你想要的數據出現,然後使用如下代碼:

string[] headings = {"Heading 1", "Heading 2", "Heading 3"}; 
string[] paragraphs = {"Content", "content again","Content even again!"}; 

literal1.Text = ""; 
for (int i=0; i<headings.Length;i++) 
{ 
    literal1.Text = string.Format("{0}<h1>{1}</h1><p>{2}</p>{3}", literal1.Text, HttpServerUtility.HtmlEncode(headings[i]), HttpServerUtility.HtmlEncode(paragraphs[i]), Environment.Newline); 
} 

請注意,我使用HttpServerUtility.HtmlEncode來編碼字符串。如果你希望包括內容(例如,如果paragraphs[0] == "<b>Content</b>「)內HTML標記,然後如果你喜歡一個List<T>和容器類,而不是刪除此方法

,該代碼可能更合適:

private class Content 
{ 
    public string Heading { get; set; }; 
    public string Paragraph { get; set; }; 
} 

private List<Content> _content = new List<Content>(); 

private void CreateContent() 
{ 
    _content.Add(new Content {Heading = "Heading 1", Paragraph = "Content"}); 
    _content.Add(new Content {Heading = "Heading 2", Paragraph = "More Content"}); 
    _content.Add(new Content {Heading = "Heading 3", Paragraph = "Even More Content"}); 

    literal1.Text = ""; 
    foreach (Content c in _content) 
    { 
     literal1.Text = string.Format("{0}<h1>{1}</h1><p>{2}</p>{3}", literal1.Text, HttpServerUtility.HtmlEncode(c.Heading), HttpServerUtility.HtmlEncode(c.Paragraph), Environment.Newline); 
    } 
}