Blog Content

    티스토리 뷰

    28.ADO.NET - Linq To DataSet

    반응형
    Linq를 이용한 DataSet 입니다.

    Form1.Designer.cs

    [그림28-1]


           private System.Windows.Forms.ListBox listBox1;

           private System.Windows.Forms.ListBox listBox2;

           private System.Windows.Forms.ListBox listBox3;


    Form1.cs

    namespace WinLinqToDataSet

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

     

            private void Form1_Load(object sender, EventArgs e)

            {

                SqlConnection con = new SqlConnection(

     "server=WINDOWS-XP\\SQLSERVER;database=AddressBook;uid=AddressBook;pwd=12345;");

     

                SqlCommand cmd = new SqlCommand();

     

                cmd.Connection = con;

     

                con.Open();

     

                cmd.CommandText = "Select * From AddressBook";

     

                cmd.CommandType = CommandType.Text;

     

                SqlDataAdapter da = new SqlDataAdapter();

     

                da.SelectCommand = cmd;

     

                DataSet ds = new DataSet();

     

                da.Fill(ds, "AddressBook");

     

                //[1] LINQ to DataSet

                // LINQ 사용해서 ListBox 아이템을 추가해보자. DataReader 해도됨.

                var q = ds.Tables[0].AsEnumerable(); // DataTable LINQ 타입으로

                var addr = from ad in q orderby ad.Field<string>("Name") select ad; // 이름 오름차순

     

                foreach (var item in addr)

                {

                    listBox1.Items.Add(item.ItemArray[1] + ", " + item.ItemArray[2]);

                }

     

                //[2] DataSet 반복. 많이 사용

                DataTable dt = new DataTable();

                dt = ds.Tables[0];

     

                for (int i = 0; i < dt.Rows.Count; i++)

                {

                    listBox2.Items.Add(dt.Rows[i]["Name"] + ", " + dt.Rows[i]["Mobile"]);

                }

     

                //[3] DataReader : 빠르다. 단순 출력 전용

                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())

                {

                    string s = dr["Name"].ToString() + ", " + dr.GetString(2);

                    listBox3.Items.Add(s);

                }

     

                dr.Close();

                con.Close();

            }

        }

    }


    결과화면

    [그림28-2]



    반응형

    'ASP.NET' 카테고리의 다른 글

    30.ADO.NET - ADO.NET 관련 클래스  (0) 2009.10.01
    29.ADO.NET - Linq To SQL  (0) 2009.09.30
    27.ADO.NET - Binding  (0) 2009.09.30
    26.ADO.NET - SqlCommandBuilder  (0) 2009.09.30
    25.ADO.NET - DataAdapter  (0) 2009.09.30

    Comments