블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
반응형

Category

Recent Post

Recent Comment

Archive

2009. 9. 29. 15:12 .Net Project/ADO.NET 3.5
반응형



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Data.SqlClient;


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

    }

    private void DisplayData()
    {
        SqlConnection con = new SqlConnection
               (ConfigurationManager.ConnectionStrings
                 ["ConnectionString"].ConnectionString);
        con.Open();

        SqlCommand cmd = new SqlCommand
                     ("Select *From Categories", con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, "Categories");

        this.ctlCategoryList.DataSource = ds.Tables[0];
        this.ctlCategoryList.DataBind();

        con.Close();
       
    }
    //추가
    protected void btnAddConnection_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings
                     ["ConnectionString"].ConnectionString;

        con.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = 
     "Insert Into Categories(CategoryName) Values(@CategoryName)";
        cmd.CommandType = CommandType.Text;
             

        //[1] 파라미터 추가하는 첫번째 방법
        //cmd.Parameters.AddWithValue

               ("@CategoryName", txtCategoryName.Text);

        //[2] 파라미터 추가하는 두번째 방법
        cmd.Parameters.Add("@CategoryName", SqlDbType.VarChar, 50);
        cmd.Parameters["@CategoryName"].Value = txtCategoryName.Text;

        //[3] SqlParamter 클래스 사용 : 
        //Sp의 Output 매개변수 처리시 무조건 사용 하여야 한다.
        //SqlParameter ParamterCategoryName =
        //new SqlParameter("@CategoryName", SqlDbType.VarChar, 50);

        //ParamterCategoryName.Direction = ParameterDirection.Input; 
        //ParamterCategoryName.Value = txtCategoryName.Text;
        //cmd.Parameters.Add(ParamterCategoryName);

       
        cmd.ExecuteNonQuery(); //실행
       
        con.Close();
        DisplayData();
    }
}




반응형
posted by Magic_kit
2009. 9. 29. 12:15 .Net Project/ADO.NET 3.5
반응형




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace 주소록
{
    public partial class MainForm : Form
    {
    
        private String connectinonString; //커넥션 스트링 저장용 필드 선언

        public MainForm()
        {
            InitializeComponent();         

            //데이터 베이스 연결문자열 지정
            connectinonString = String.Format (
                "server=.;database={0};uid={0};pwd=1234;", "AddressBook");
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
           DisplayData();
        }
        private void LoadData()
        {             
            DisplayData();
        }

                                             ↓



//Dataset을 필드 레벨로 옮겨서 다른서 메서드에서 사용가능하도록 한다 .
      
         DataSet ds; //현패 폼에서 공통적으로 사용할 DataSet개
        // 출력
        private void DisplayData()
        {
            SqlConnection con = new SqlConnection(connectinonString);
            con.Open(); //연결

            SqlCommand cmd = new SqlCommand
                       ("Select *From AddressBook", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds, "AddressBook");

            this.dgvAddress.DataSource = ds.Tables[0].DefaultView;
           
            con.Close(); //닫기

            if (ds.Tables[0].Rows.Count > 0)
            {
                ShowRecord(0); //첫번째 자료로 초기화
                currentIndex = 0;
            }
            sslCount.Text = ds.Tables[0].Rows.Count.ToString();
        }

                                    ↓

  


      private void btnSave_Click(object sender, EventArgs e)
        {
              SaveData();
        }
----------------------------------------------------------------------
        private void SaveData()
        {

            SqlConnection con = new SqlConnection(connectinonString);
            con.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "Insert Into AddressBook Values
                                         (@Name, @Mobile, @Email)";
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
            cmd.Parameters.AddWithValue("@Email", txtEmail.Text);

            cmd.ExecuteNonQuery() ; //저장
            c
on.Close();
            ClearTextBox();
            MessageBox.Show("저장되었습니다.");
            DisplayData(); //호출 하여 재 바인딩
        }

                                     ↓

     

 
       // 백업
        private void miBackup_Click(object sender, EventArgs e)
        {
            try
            {
                string dir = "C:\\AddressBook.xml";
                //해당 폴더에는 NTFS파일 시스템 권한이 필요
                ds.WriteXml(dir); //XML 형태로 저장

                MessageBox.Show("백업 완료");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
----------------------------------------------------------------------

       // 종료  
       private void miExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private int currentIndex = -1;

        //셀 클릭하였을 경우 선택한값 텍스트 박스에 표시
        private void dgvAddress_CellClick(object sender,
            DataGridViewCellEventArgs e)
        {
            currentIndex = e.RowIndex; // 현재 인덱스를 필드에 보관

            if (e.RowIndex < ds.Tables[0].Rows.Count)
            {
                ShowRecord(e.RowIndex);
            }

        }

                                      ↓ 

 


        //상세
        private void ShowRecord(int index)
        {
            DataRow dr = ds.Tables[0].Rows[index];
           
            this.txtNum.Text = dr["Num"].ToString();
            this.txtName.Text = dr["Name"].ToString();
            this.txtMobile.Text = dr["Mobile"].ToString();
            this.txtEmail.Text = dr["Email"].ToString();
         
            txtGo.Text = txtNum.Text; //현재 선택 된 인덱스값 출력
        }

        //수정
        private void btnModify_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectinonString);
            con.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "Update AddressBook
                      Set Name = @Name, Mobile = @Mobile, Email = @Email
                                        Where Num = @Num";

            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@Name", txtName.Text);
            cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
            cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@Num", txtNum.Text);

            cmd.ExecuteNonQuery();
            con.Close();

            MessageBox.Show("수정되었습니다");
            ClearTextBox();
            DisplayData();

            ShowRecord(currentIndex);
        }

        //삭제
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (txtNum.Text != "" && currentIndex != -1)
            {
                DialogResult dr =
                    MessageBox.Show("정말로 삭제하시겠습니까?",
                           "삭제확인" , MessageBoxButtons.YesNo, 
                                          MessageBoxIcon.Question);
                if (dr != DialogResult.No)
                {
                    // 실제 DB에서 삭제
                    DeleteData(); //호출
                    DisplayData();
                }
            }
        }

        private void DeleteData()
        {
            SqlConnection con = new SqlConnection(connectinonString);
            con.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText =
                   "Delete AddressBook Where Num = @Num";
            cmd.CommandType = CommandType.Text;
           
            //파라미터 추가
            cmd.Parameters.AddWithValue("@Num", txtNum.Text);
           
            cmd.ExecuteNonQuery(); //삭제 실행
            con.Close();
            MessageBox.Show("삭제되었습니다");
            ClearTextBox();               
        }

                                   ↓


 
// 처음, 이전, 다음, 마지막 버튼에 대한 공통 이벤트
        private void btnMove_Click(object sender, EventArgs e) {
            Button btn = sender as Button;
            if (btn == btnFirst) {
                if (currentIndex > 0) {
                    currentIndex = 0; // 0번째 인덱스로 표시
                    }
                MessageBox.Show("더이상 가실수 없습니다");          
            }
            else if (btn == btnPrev) {
                if (currentIndex > 0) {
                    currentIndex--;
                }
                MessageBox.Show("더이상 가실수 없습니다");
            }
            else if (btn == btnNext) {
                if (currentIndex < ds.Tables[0].Rows.Count - 1) {
                    currentIndex++;
                }
            }
            else if (btn == btnLast) {
                if (currentIndex != -1) {
                    currentIndex = ds.Tables[0].Rows.Count - 1;
                }
            }
            ShowRecord(currentIndex); // 다시 데이터 표시
        }

        //이동
        private void btnGo_Click(object sender, EventArgs e)
        {
            if (txtGo.Text != "" && Convert.ToInt32(txtGo.Text) > 0) 
            {
                int go = Convert.ToInt32(txtGo.Text);

                DataRow dr;
                bool flag = false ;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                 {
                    dr= ds.Tables[0].Rows[i];
   
                    if (go == Convert.ToInt32(dr["Num"]))
                    {
                        txtNum.Text = dr["Num"].ToString();
                        txtName.Text = dr["Name"].ToString();
                        txtMobile.Text = dr["Mobile"].ToString();
                        txtEmail.Text = dr["Email"].ToString();
                     
                        flag = true;
                     }   
              }
                if(flag == false)
                {
                    MessageBox.Show("찾지못했습니다");
                }
                txtGo.Select();
            }
        }
        // 검색
        private void btnSearch_Click(object sender, EventArgs e)
        {
            DataView ddv = ds.Tables[0].DefaultView;
            ddv.RowFilter =
                    "Name Like '%" + txtSearch.Text + "%' Or "
                    + "Mobile Like '%" + txtSearch.Text + "%' Or "
                    + "Email Like '%" + txtSearch.Text + "%'";

            this.dgvAddress.DataSource = ddv;          
        }

        //텍스트박스 클리어
        private void button1_Click(object sender, EventArgs e)
        {
            ClearTextBox(); //텍스트박스 클리어
        }
    }








반응형
posted by Magic_kit
2009. 9. 28. 15:24 .Net Project/ADO.NET 3.5
반응형

 RowFilter : 데이터 검색시 사용하는 속성 : "CategoryName" Like '%컴퓨터%'"
        Connection -> Command -> DataAdapter -> DataSet ->
        DataTable -> DataView -> DataView.RowFilter 속성

DataView에 표시할 행을 필터링하는 데 사용하는 식을 가져오거나 설정


using System.Configuration;
using System.Data;
using System.Data.SqlClient;

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

        //커넥션
        SqlConnection con = new SqlConnection
                          (ConfigurationManager.ConnectionStrings
                           ["ConnectionString"].ConnectionString);
        con.Open();

        //커멘드
        SqlCommand cmd = new SqlCommand
                    ("Select *From Categories", con);
       
        cmd.CommandType = CommandType.Text;

        //어댑터
        SqlDataAdapter da = new SqlDataAdapter(cmd); //초기화
        DataSet ds = new DataSet();
        da.Fill(ds, "Categories");

        //전체출력
        this.ctlSearchList.DataSource = ds;
        this.ctlSearchList.DataBind();
        
        con.Close();
      
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection
                     (ConfigurationManager.ConnectionStrings
                      ["ConnectionString"].ConnectionString);
        con.Open();

        SqlCommand cmd = new SqlCommand
                   ("Select *From Categories", con);
        cmd.CommandType = CommandType.Text;

        SqlDataAdapter da = new SqlDataAdapter(cmd); //초기화
        DataSet ds = new DataSet();
        da.Fill(ds, "Categories");

        //전체출력 
        this.ctlSearchList.DataSource = ds;
        this.ctlSearchList.DataBind();

       
        //[1]DataTable변환
        DataTable dt = ds.Tables[0];

        //[2]DataView 변환
        DataView dv = dt.DefaultView;

        //[3]DataView.RowFilter변경
        dv.RowFilter = "CategoryName Like '%" + txtSerchquery.Text + "%'";
        dv.Sort = "CategoryName Asc"; //정렬

        this.ctlSearchList.DataSource = dv;
        this.ctlSearchList.DataBind();
       
        con.Close();
   }
}






반응형
posted by Magic_kit
2009. 9. 28. 15:23 .Net Project/ADO.NET 3.5
반응형

DataRow 개체와 DataColumn 개체는 DataTable의 기본 구성 요소입니다.
DataRow 개체 및 해당 속성과 메서드를 사용하여 DataTable의 값을 검색, 계산, 삽입, 삭제 및 업데이트합니다.

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class Category_FrmDataRow : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Display();
        }
    }

    private void Display()
    {
        //커넥션
        SqlConnection con = new SqlConnection
                 (ConfigurationManager.ConnectionStrings
                  ["ConnectionString"].ConnectionString);

        con.Open();
      
        //커맨드
        SqlCommand cmd = new SqlCommand
                  ("Select *From Categories",con);
        cmd.CommandType = CommandType.Text;

       //어댑터
 
        SqlDataAdapter da = new SqlDataAdapter(cmd); //초기화

        DataSet ds = new DataSet();

        da.Fill(ds, "Categories");

        this.lstCategoryList.DataSource = ds;
        this.lstCategoryList.DataTextField = "CategoryName";//보이는
        this.lstCategoryList.DataValueField = "CategoryID"; //안의 값
        this.lstCategoryList.DataBind();

        con.Close();
    }
}


- Typically populated from database
- Use DataRow
 
 //List<T>와 같은 방법으로 출력
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
             //한개의 레코드를 DataRow에 담기 
             DataRow dr = ds.Tables[0].Rows[i] ;
            
             //[1]lstCategoryList.Items.Add(dr["CategoryID"].ToString());

             //[2] 가장 일반적인 사용방법
            lstCategoryList.Items.Add(new ListItem(dr
               ["CategoryName"].ToString(),
dr["CategoryID"].ToString()));
        }






반응형
posted by Magic_kit
prev 1 2 3 4 5 6 7 next