ASP.NET利用String.Join以分隔符號來串連集合資料

最近看到string有join這個用法..還不錯用..介紹給大家呀...
有時我們會將一個集合資料以","分隔組合成一字串..例如:aaa,bbb,ccc
利用String.Join就可以做到了...省下很多程式碼的判斷....

最近看到string有join這個用法..還不錯用..介紹給大家呀...

有時我們會將一個集合資料以","分隔組合成一字串..例如:aaa,bbb,ccc

利用String.Join就可以做到了...省下很多程式碼的判斷....

asp.net(c#)

strJoin.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="strJoin.aspx.cs" Inherits="strJoin" %>

strJoin
    <asp:CheckBoxList ID="CheckBoxList1" runat="server" 
        RepeatDirection="Horizontal">
        <asp:ListItem>F6 Team</asp:ListItem>
        <asp:ListItem>Puma</asp:ListItem>
        <asp:ListItem>Dotblogs</asp:ListItem>
        <asp:ListItem>tech‧ed 2008</asp:ListItem>
    </asp:CheckBoxList>
    <br />
    <asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Join" />

</div>
</form>

strJoin.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

public partial class strJoin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
    List<string> list = new List<string>();

    foreach (ListItem item in this.CheckBoxList1.Items)
    {
        if (item.Selected)
        {
            list.Add(item.Text);
        }
    }

    this.TextBox1.Text = string.Join(",",list.ToArray());
}

}

執行結果:

posted @ 2016-01-28 14:36  冰封的心  阅读(742)  评论(0编辑  收藏  举报