c#
  • windows-forms-designer
  • 2013-08-23 2 views 1 likes 
    1

    DataGridView을 업데이트하여 데이터베이스에 변경 사항을 적용하려면 어떻게해야합니까?Datagridview 업데이트

    foreach (DataGridViewRow myDgrow in dataGridView2.Rows) { 
        myCmd = "Update Details set ProjectName='" 
          + myDgrow.Cells["ProjectName"].Value 
          + "', Description = '" 
          + myDgrow.Cells["Description"].Value 
          + "', DateStarted='" 
          + myDgrow.Cells["DateStarted"].Value 
          + "',TeamSize='" 
          + myDgrow.Cells["TeamSize"].Value 
          + "',Manager='" 
          + myDgrow.Cells["Manager"].Value 
          + "'"; 
    
        myCmd = "Update Details set Description = '" 
          + myDgrow.Cells["Description"].Value 
          + "', DateStarted='" 
          + myDgrow.Cells["DateStarted"].Value 
          + "',TeamSize='" 
          + myDgrow.Cells["TeamSize"].Value 
          + "',Manager='" 
          + myDgrow.Cells["Manager"].Value 
          + "' where ProjectName='" 
          + myDgrow.Cells["ProjectName"].Value 
          + "'"; 
    
        cmd.Parameters.AddWithValue("@projectName1", myDgrow.Cells["ProjectName"].Value); 
        cmd.Parameters.AddWithValue("@Description1", myDgrow.Cells["Description"].Value); 
        cmd.Parameters.AddWithValue("@DateStarted1", myDgrow.Cells["DateStarted"].Value); 
        cmd.Parameters.AddWithValue("@TeamSize1", myDgrow.Cells["TeamSize"].Value); 
        cmd.Parameters.AddWithValue("@Manager1", myDgrow.Cells["Manager"].Value); 
        cmd.CommandText = myCmd; 
    
        dataGridView2.Update(); 
    
        //cmd.Parameters.Clear(); 
        cmd.ExecuteNonQuery(); 
        myCmd = string.Empty; 
    } 
    
    +0

    call dataGridView2.Update(); cmd.ExecuteNonQuery(); 그리고 다시 시도하십시오 – Sumeshk

    +0

    가능한 중복 [DataGridView 데이터베이스 업데이트] (http://stackoverflow.com/questions/18459416/datagridview-updating-database) – Bridge

    답변

    1

    좋아 다시 시도, 그래서 이것은 당신이 원하는 무엇인가 : 내가 노력하고 코드는

    using (SqlConnection c = new SqlConnection(connString)) 
    using (SqlCommand cmd = new SqlCommand(sql, c)) 
    { 
        cmd.Parameters.AddWithValue("@field1", myDgrow.Cells["field1"].Value); 
        ... 
    
        cmd.ExecuteNonQuery(); 
    } 
    

    sql 뭔가를 보일 수 있습니다 like :

    UPDATE table SET field1 = @field1, field2 = @field2 WHERE fieldId = @fieldId 
    

    이고 루프는 foreach 루프 안에 반복 할 때마다 그렇게 할 것입니다.

    myCmd을 두 개의 다른 것으로 연속 설정하고 사용하고 있지 않기 때문에 솔직하게 코드에서 무엇을하는지 알지 못합니다. 그래서 나는 cmd 객체가 가지고있는 SQL을 알지 못한다. 따라서 코드를 수정하여 앞에서 설명한 구조를 사용하면 예상대로 작동합니다.

    참고 : 사용자가 데이터 그리드에 추가 할 수있는 경우는 나도 몰라,하지만이 경우는 INSERT 문이어야 할 필요가 있기 때문에, 다른 sql을 구축 할 수 있습니다.

    1

    cmd.ExecuteNonQuery(); 후 전화 dataGridView2.Update();

    관련 문제