2013-08-22 22 views
1

我有一個DataGrid(grid_detail),因爲我現在已經只閱讀它的單排和保存到數據庫中使用的代碼如下迴路中,從而讀取C#DataGridView的幾行

  //number of columns actually in second dgv 
      int col_no = grid_detail.ColumnCount; 
      int row_no = grid_detail.RowCount - 1; 
      int r = 0; 



      //array to contain the values of the cells 
      string[] col_value = new string[100]; 
      for (i = 0; i < col_no; i++) 
      { 
       //fill in the Array with values from cells 
       col_value[i] = Convert.ToString(grid_detail.Rows[0].Cells[i].Value); 
      } 
      //Build insert command 
      StringBuilder Q = new StringBuilder(); 
      Q.Append("INSERT INTO "); 
      Q.Append("[Ref].["); 
      Q.Append(_lstview_item); 
      Q.Append("]"); 
      Q.Append(" VALUES"); 
      Q.Append("("); 
      for (i = 0; i < col_no; i++) 
      { 
       Q.Append("'"); 
       if (string.IsNullOrEmpty(col_value[i])) 
       { 
        x = false; 
        break; 
       } 
       else 
       { 
        Q.Append(col_value[i]); 
        Q.Append("'"); 
        Q.Append(","); 
        x = true; 
       } 
      } 
      //removing last COMMA from loop 
      if (col_no > 0) 
      { 
       Q.Length--; 
      } 
      Q.Append(")"); 
      query = Q.ToString(); 



      if (x == true) 
      { 
       //open connection to db and send query 
       SqlConnection conn = new SqlConnection(cc.connectionString(cmb_dblist.Text)); 
       SqlCommand cmd_server = new SqlCommand(query); 
       cmd_server.CommandType = CommandType.Text; 
       cmd_server.Connection = conn; 
       conn.Open(); 
       cmd_server.ExecuteNonQuery(); 
       conn.Close(); 

然而,我的要求是,我現在閱讀了一行Z網格並保存到數據庫。 我試圖用一個for循環的行數像

for (r=0;r<row_no;r++) 
{ 

/////CODES ABOVE PASTED HERE 

} 

我不能做循環。

請幫忙。

回答

1

我假設你根據grid_detail行數有row_no集,然後再做修改和測試

for (int r=0; r< grid_detail.RowCount; r++) 
{ 
    // your code... 
    //int r = 0; comment this line 
    // your code... 
    //............. 
      for (i = 0; i < col_no; i++) 
      { 
       //fill in the Array with values from cells 
       col_value[i] = Convert.ToString(grid_detail.Rows[r].Cells[i].Value); // use row r 
      } 
    //............. 
    // your code... 

} 

以下,但我會重新因素代碼下面

foreach (GridViewRow row in GridView1.Rows) 
{ 
    string sql = GenerateSql(row); 
    if (!string.IsNullOrEmpty(sql)) 
     ExecuteNonQuery(sql); 
} 
private void ExecuteNonQuery(string query) 
{ 
    using (SqlConnection conn = new SqlConnection(connectionString)) 
    using (SqlCommand cmd_server = new SqlCommand(query, conn)) 
    { 
     conn.Open(); 
     cmd_server.ExecuteNonQuery(); 
    } 
} 

private string GenerateSql(GridViewRow row) 
{ 
    var values = row.Cells.Cast<TableCell>().Select(x => x.Text).ToArray(); 
    if (values.Any(string.IsNullOrEmpty)) 
    { 
     return string.Empty; 
    } 
    var sql = string.Format("INSERT INTO [Ref].[{0}] VALUES ({1})", _lstview_item, string.Join(",", values)); 

    return sql;  

} 
+0

hnxx我prblm解決。 –