1. Select 하여 DataGridView에 뿌려주기

try

{

// 1. 데이터베이스 연결설정

conn = new SqlConnection("Server = Localhost; user id = sa; database = hanvit");

// 2. 데이터베이스 연결

conn.Open();

 

//2. 명령 객체 생성 및 [SQL, 연결객체] 설정

SqlCommand cmd = new SqlCommand("SELECT TOP 1000 *  FROM DGPS order by refid asc", conn);

 

// 3. 데이터 처리 어댑처 사용

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

 

da.Fill(ds, "DGPS");  //DataSEt DGPS 테이블 만들고 그 테이블에 데이터를 저장

 

DataGridView1.DataSource = ds; //DataGridViewDataSet(일종의 DB) 연결 후

DataGridView1.DataMember = "DGPS";  //DataSet 안의 테이블 명을 DataMember에 지정

 

}

catch (SqlException x)

{

    this.textbox1.AppendText(x.Message);

}




2. DataGridView 로 불러온 DATA 수정하면 바로 DB에 업데이트 하기

private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)

{

try

{

//업데이트 구문 UPDATE [TABLE] SET [속성값] = [새데이터] WHERE [조건]

//UPDATE Sales.ContactCreditCard SET CreditCardID = 1 WHERE ContactID = 2

string str = "UPDATE Sales.ContactCreditCard SET " + DataGridView.Columns[e.ColumnIndex].Name + " = " + DataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() + " WHERE " + DataGridView.Columns[0].Name + " = " + DataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();

 

SqlCommand cmd = new SqlCommand(str, conn);

cmd.ExecuteNonQuery();

}

catch (SqlException x)

{

}

}






 

Posted by motolies
,