Thursday, 27 December 2012

How to Get List Items into Comma Separated in a single string .

How to Get List Items into Comma Separated in a single string .






 Aspx Page:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <br />
    <br />
    <br />
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
        Text="Data Table" />
    </form>
</body>
</html>


Aspx.cs Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
//Global Variable
List<string> l = new List<string>();
string s = string.Empty;
            DataTable dt = new DataTable();
            DataRow dr;


protected void  Button1_Click(object sender, EventArgs e)
{
    //Getting  Comma Seperate String from List Item

    for (int i = 0; i < 9; i++)
    {
        l.Add(i.ToString());
    }

    s = string.Join(",", l.ToArray());
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + s + "')", true);
}



    protected void Button2_Click(object sender, EventArgs e)
    {
        // Getting Comma Seperate string from table's First column.
  
        dt.Columns.Add("No");
        for (int i = 1; i < 10; i++)
        {
             dr = dt.NewRow();
            dr["No"] =  i.ToString();
            dt.Rows.Add(dr);
        }
       


        s = string.Join(",", ((List<string>)dt.AsEnumerable().Select(x => x[0].ToString()).ToList()).ToArray());
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + s + "')", true);
    }
}


0 comments: